2011-07-20 45 views
0

为什么我不能声明var myVar =“myvariable”作为类中的全局变量?有没有办法做到这一点?在函数外声明var

+1

那么'class'有什么用? – Rahul

+0

[为什么class字段不能是var?]的可能的重复(http://stackoverflow.com/questions/4461597/why-class-fields-cannot-be-var) –

回答

3

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var

由于C#规范,它们只处于方法范围。

9

why i can't declare for example var myVar="myvariable" as a global variable in a class?.

因为那是designers of the C# language决定如何执行它。

Is there any way to do it?.

不,没有。

+0

你能说明原因吗?为什么设计师会采取这个决定? – naveen

+0

@naveen,你读过我链接到的博客文章:http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx它的写作由C#编译器的设计人员之一,并在其中解释原因。 –

+0

不,我不喜欢。在提交之前,我在之前的文章中编辑过eric lippert作为设计师。 – naveen

0

var是一个关键字,通常用于匿名类型。 然后声明字段或全局变量,您必须明确设置字段的实际类型。

From MSDN:

  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

  • var cannot be used on fields at class scope.

  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20) ; but this expression produces a compile-time error: var i = (i = 20) ;

  • Multiple implicitly-typed variables cannot be initialized in the same statement.

  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

参见: Eric Lippert opinion

1

没有,VAR只对局部范围的变量。请参阅this

0

隐式类型只能作为局部变量放在方法范围中。

0

我认为你正在寻找一个静态变量。

例如

public class AGlobalVar 
{ 
    public static int AVar = 10; 

} 

你应该能够在任何地方访问变量的应用。要访问它只需去AGlobalVar.AVariable。