问题
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;
}
回答1:
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;
}
回答2:
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;
}
来源:https://stackoverflow.com/questions/38260309/how-to-declare-a-variable-that-can-be-used-by-every-method-c-sharp