是否可以使用“ var”标记作为全局变量 [英] Is it possible to have a "var" as a Global variable

查看:161
本文介绍了是否可以使用“ var”标记作为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到c#中的全局变量上还有其他线程。例如整数,字符串等。

I have noticed there are other threads on global variables in c#. Such as integers, strings etc. e.g.

public static int;

但是我需要使用另一个线程未提及的 var和

But I need to use a "var" which the other thread don't mention and

public static var;

似乎不起作用。

所以我要问的是在c#中是否可以将 var作为全局变量?

So what I'm asking is it possible to have a "var" as a global variable in c#?

推荐答案

C#规范(第26.1节)内容如下:

C# specification (section 26.1) reads:

[`var是]隐式类型的局部变量声明...

[`var is] an implicitly typed local variable declaration ...

进一步:


隐式类型局部变量
声明中的局部变量声明符受以下限制:

A local variable declarator in an implicitly typed local variable declaration is subject to the following restrictions:


  • 声明器必须包括一个初始化器。

  • 该初始化器必须是一个表达式。

  • 该初始化器表达式必须具有编译时类型

  • 局部变量声明不能包含
    个多个声明符。

  • 初始化器无法引用到声明的变量ite lf

  • The declarator must include an initializer.
  • The initializer must be an expression.
  • The initializer expression must have a compile-time type which cannot be the null type.
  • The local variable declaration cannot include multiple declarators.
  • The initializer cannot refer to the declared variable itself

所以不,您不能这样做。此外,我建议不要考虑全局变量。

So no, you cannot do this. Moreover I would recommend steering away from even thinking about global variables.

语言不支持全局变量。您可能会在 public static 字段中找到替代方法,但这会泄漏对象状态并破坏封装。

Global variables are not supported by the language. You may find alternatives in public static fields, but this will leak object state and break encapsulation.

这篇关于是否可以使用“ var”标记作为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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