[英]How to declare a variable that can be used by every method? | C#
I want to ask you how to declare a variable that can be used by every method?我想问你如何声明一个可以被每个方法使用的变量?
I tried making the method's access type public but that didn't let me used its variable across other methods我尝试将方法的访问类型设为公开,但这并没有让我在其他方法中使用它的变量
Moreover, I basically want to accumulate that variable with different values across different methods that's why I am asking this.此外,我基本上想在不同的方法中累积具有不同值的变量,这就是我问这个的原因。
NOTE: I want to avoid making any static classes.注意:我想避免创建任何静态类。
EDIT:编辑:
For example, I did例如,我做了
public decimal MiscMethod()
{
decimal value1 += 23m;
}
public decimal AutoMethod()
{
decimal value 1 += 34;
}
do you mean somethinge like this ?你的意思是这样的吗?
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.Print(); //Output: Hello
myClass.SetVariable();
myClass.Print(); //Output: Test
}
}
class MyClass
{
string MyGlobaleVariable = "Hello"; //my global variable
public void SetVariable()
{
MyGlobaleVariable = "Test";
}
public void Print()
{
Console.WriteLine(MyGlobaleVariable);
}
}
with your example:用你的例子:
decimal value1 = 0;
public decimal MiscMethod()
{
value1 += 23m;
}
public decimal AutoMethod()
{
value1 += 34;
}
Use it like a global variable,but make sure after using it in every method you need to nullify the value,as that will not make the value contradictory to other methods.像全局变量一样使用它,但请确保在每个方法中使用它后都需要取消该值,因为这不会使该值与其他方法相矛盾。
decimal value1;
public decimal MiscMethod()
{
value1 += 23m;
//Complete your code using value1
value1 = 0;
}
public decimal AutoMethod()
{
value 1 += 34;
//Complete your code using value1
value1 = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.