为什么我不能声明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声明期望声明
- 2. 用var或不用var声明一个函数会更好吗?
- 3. 在JavaScript中使用var关键字在函数外声明变量
- 4. 在函数之外声明变量
- 5. 如何在类声明之外声明模板函数
- 6. JS函数声明:在参数声明
- 7. 声明VAR VS在JS
- 8. 在函数中声明的var在多个函数调用中是否存在?
- 9. 是“T var();”总是在C++中的函数声明?
- 10. 在javascript中声明函数时,我必须使用`var`吗?
- 11. 函数声明
- 12. 外部助手函数声明?
- 13. C#中的DLL外部函数声明#
- 14. VAR VS显式声明
- 15. 声明函数在JavaScript
- 16. 声明函数,在签名
- 17. 函数在声明之前
- 18. 声明函数在C++
- 19. jQuery函数声明说明
- 20. JSLint错误:将所有'var'声明移到函数顶部
- 21. 变量声明的语法? VAR A =(函数(){})()
- 22. jQuery函数声明
- 23. (Z3Py)声明函数
- 24. PLSQL函数声明
- 25. C++函数声明
- 26. 使用var在Javascript中声明变量
- 27. 在MVC中的页面中声明“var”
- 28. 无法声明var a = 023;在JS
- 29. 在声明函数之外的二维数组中访问struct
- 30. 函数声明使用perl函数指针声明
那么'class'有什么用? – Rahul
[为什么class字段不能是var?]的可能的重复(http://stackoverflow.com/questions/4461597/why-class-fields-cannot-be-var) –