简体   繁体   English

如何在C#中声明一个应该可以被项目中的所有类访问的公共变量?

[英]How do I declare a public variable in C# that should be accessible to ALL classes in the project?

I have a list as follows in a class: 我在课堂上有如下列表:

public string[] Locations = { "home",
                              "office",
                              "vehicle" };

(The actual string/list is hundreds of items long I just shortened it for the sake of this post) (实际的字符串/列表是数百个项目,我只是为了这个帖子缩短了它)

In another class, I am trying to reference it with: 在另一个类中,我试图引用它:

string location = Locations[myRand.Next(Locations.Length)];

Though it does not recognize "locations" as a string. 虽然它不会将“位置”识别为字符串。

How do I make it to where all the classes can see it? 如何将它带到所有类可以看到的位置? Also, do they have to be within the same namespace for this to work? 此外,它们是否必须位于相同的命名空间内才能工作? Or is there a way to make the list available to ALL namespaces and classes? 或者有没有办法使列表可用于所有名称空间和类?

Thanks! 谢谢!

By declaring it as public it is already visible to all namespaces. 通过将其声明为public它已经可见所有命名空间。 The issue is how to access it. 问题是如何访问它。 What you want is static : 你想要的是static

public class MyClass
{
    public static string[] Locations = { "home",
                          "office",
                          "vehicle" };
}

Then you access it as: 然后你访问它:

string s = MyClass.Locations[1];

If it's not static, then you need an instance of the class to access it: 如果它不是静态的,那么你需要一个类的实例来访问它:

MyClass m = new MyClass();
string s = m.Locations[1];

Seems like you want a "utils" function, to be called anywhere. 好像你想要一个“utils”函数,可以在任何地方调用。 Maybe create a new workspace for "utilities, and declare your function static in a file inside that workspace as Ian said. 也许为“实用程序创建一个新的工作区,并在Ian说的那个工作区内的文件中声明你的函数是静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM