6

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

public static int;

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

public static var;

doesn't seem to work.

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

4

2 回答 2

6

No, because var is not a type itself, it merely takes on the form of whatever expression is on the righthand side of the assignment:

var num = 1;

is the same as:

int num = 1;

when declaring variables that are scoped outside of a method, you need to use the full type designator:

public static int num = 1;

or

public static int Num {get;set;}

etc

于 2013-01-28T22:50:30.313 回答
6

C# specification (section 26.1) reads:

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

It goes further:

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

  • 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.

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.

于 2013-01-28T23:00:59.400 回答