2011-07-20 99 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。