宣告全球可变 [英] declaration of global varaiable

查看:58
本文介绍了宣告全球可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应该在其中声明要在整个项目中使用的变量.

where we should we declare the variable that is to be used in whole project.

推荐答案

C#没有全局变量",因此没有这样的变量可以在整个项目中使用的变量.
您可以使用静态变量来复制它,尤其是当它在静态类中时:
C# does not have "global variables", so there is no such variable that can be used in the whole project.
You can duplicate this with a static variable, particularly if it is in a static class:
public static class Globals
   {
   public static string globalString = "hello";
   }

您可以使用它:

string s = Globals.globalString;


但是,您实际上很少需要它.
您想做什么,以为您只能与全球性公司合作?

[edit]添加了使用示例-OriginalGriff [/edit]


However, it is pretty rare that you actually should need this.
What are you trying to do that you think you can only do with a global?

[edit]Added use example - OriginalGriff[/edit]


这些将进入静态类.
如果您不希望将它们设置为其他位置,请将它们标记为readonly.
These would go into a static class.
Mark them as readonly if you don''t wanted them set anywhere else.


您最好避免使用真正的全局变量.首选实例变量.通常,每个应用程序只有一个对象.例如,对于UI,您具有主Form或主Window以及单个Application对象.使您的对象成为此类单个对象的字段,创建访问此字段的属性,并为此属性指定访问权限internal.

在其他情况下,您可以具有入口点("main")方法的堆栈变量,并将此变量传递给需要使用它的所有方法.

最好不要使用全局变量.如果您仍然想要全局的东西,请实施singleton design pattern,请参见 http://en.wikipedia.org/wiki/Singleton_pattern [ ^ ].

有关单例的更多说明,请参见以下讨论:
关于设计模式Singleton和Factory [
You should better avoid the really global variable. Prefer instance variable. You usually have some single object per application. For example, with UI you have main Form or main Window and also single Application object. Make your object a field of such single object, create a property accessing this field, make access specifier for this property internal.

In other cases, you can have a stack variable of your entry point ("main") method and pass this variable to all methods which needs to use it.

Not using a global variable is the best option. If you still want a global thing, implement singleton design pattern, see http://en.wikipedia.org/wiki/Singleton_pattern[^].

For more directions on singletons, please see this discussion:
About Design Patterns Singleton and Factory[^].

—SA


这篇关于宣告全球可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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