爲什麼我不能聲明var myVar =「myvariable」作爲類中的全局變量?有沒有辦法做到這一點?在函數外聲明var
回答
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var
由於C#規範,它們只處於方法範圍。
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?.
不,沒有。
var
是一個關鍵字,通常用於匿名類型。 然後聲明字段或全局變量,您必須明確設置字段的實際類型。
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.
沒有,VAR只對局部範圍的變量。請參閱this
隱式類型只能作爲局部變量放在方法範圍中。
我認爲你正在尋找一個靜態變量。
例如
public class AGlobalVar
{
public static int AVar = 10;
}
你應該能夠在任何地方訪問變量的應用。要訪問它只需去AGlobalVar.AVariable。
- 1. Var聲明在Javascript
- 2. var聲明期望聲明
- 3. 用var或不用var聲明一個函數會更好嗎?
- 4. 在JavaScript中使用var關鍵字在函數外聲明變量
- 5. 在函數之外聲明變量
- 6. 如何在類聲明之外聲明模板函數
- 7. JS函數聲明:在參數聲明
- 8. 聲明VAR VS在JS
- 9. 在函數中聲明的var在多個函數調用中是否存在?
- 10. 是「T var();」總是在C++中的函數聲明?
- 11. 在Scala中聲明一個使用def或var的函數
- 12. 在javascript中聲明函數時,我必須使用`var`嗎?
- 13. 外部函數局部聲明
- 14. C#中的DLL外部函數聲明#
- 15. 外部助手函數聲明?
- 16. Fortran 1中的意外聲明函數
- 17. 函數聲明
- 18. 聲明函數
- 19. 聲明函數
- 20. 聲明:var = property(lambda self:object())
- 21. ENV VAR包括聲明
- 22. VAR VS顯式聲明
- 23. Node.js上VAR的聲明
- 24. 聲明函數在JavaScript
- 25. 函數聲明在多行
- 26. 聲明函數在C++
- 27. 函數在聲明之前
- 28. 聲明函數,在簽名
- 29. jQuery函數聲明說明
- 30. JSLint錯誤:將所有'var'聲明移到函數頂部
那麼'class'有什麼用? – Rahul
[爲什麼class字段不能是var?]的可能的重複(http://stackoverflow.com/questions/4461597/why-class-fields-cannot-be-var) –