如何声明每个方法都可以使用的变量?|C# [英] How to declare a variable that can be used by every method? | C#
本文介绍了如何声明每个方法都可以使用的变量?|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.
例如,我做了
public decimal MiscMethod()
{
decimal value1 += 23m;
}
public decimal AutoMethod()
{
decimal value 1 += 34;
}
推荐答案
您的意思是这样的吗?
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);
}
}
与您的示例:
decimal value1 = 0;
public decimal MiscMethod()
{
value1 += 23m;
}
public decimal AutoMethod()
{
value1 += 34;
}
这篇关于如何声明每个方法都可以使用的变量?|C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文