在类中初始化全局变量 [英] Initializing global variable in a class

查看:207
本文介绍了在类中初始化全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想在运行时在类中初始化一个全局变量..这可能吗?还有其他方式吗?



即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

推荐答案

这里有几个问题:首先关闭C#没有全局变量:一切都在一类。你可以得到的最接近的是在一个类中有一个静态变量,并且可以通过类名对整个代码使用:

There are a couple of problems here: first off C# doesn;t have global variables: everything is within a class. The closest you can get is to have a static variable inside a class and that will be available to the whole code via the class name:
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.


这篇关于在类中初始化全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆