问题描述
我想在运行时在类中初始化一个全局变量..这可能吗?还有其他方式吗?
即console.writeline(输入路径)
string path = console.readline();
现在我只初始化了它的主要方法..但是我有几个其他方法应该使用这个变量路径
我尝试了什么:
尝试将主要方法放在一边
声明变量为static ..在执行期间它返回null
Hi,
I would like to initialize a global variable inside a class during run time..is it possible?Any other way?
i.e console.writeline("Enter the path")
string path=console.readline();
Right now I have initialized only main method it works..however i have couple of other methods where this variable "path" should be used
What I have tried:
Tried placing out side the main method
declared the variable as static .. during execution it returns null
推荐答案
public class MyClass
{
public static int globalValue = 666;
...
}
...
public class MyOtherclass
{
private void MyMethod()
{
Console.WriteLine(MyClass.globalValue);
}
}
当你这样做时,可以使用MyClass的静态构造函数来初始化变量:
When you do that, you can use a static constructor for MyClass to initialize the variable:
public class MyClass
{
public static string globalValue;
static MyClass()
{
globalValue = File.ReadAllText(@"D:\Test Data\Primes.txt");
}
}
在使用变量之前将调用静态构造函数。
The static constructor will be called before the variable is used.
这篇关于在类中初始化全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!