<分区>
我喜欢在 C# 中为局部变量隐式键入:
var Beer = new Malt.Beer();
代替:
Malt.Beer Beer = new Malt.Beer();
我不认为这可以扩展到字段,对吗?
public var Beer = new Malt.Beer();
代替:
public Malt.Beer Beer = new Malt.Beer();
它无法编译,但想知道我是不是语法错误或隐式变量 (var) 不能在此范围内使用?
<分区>
我喜欢在 C# 中为局部变量隐式键入:
var Beer = new Malt.Beer();
代替:
Malt.Beer Beer = new Malt.Beer();
我不认为这可以扩展到字段,对吗?
public var Beer = new Malt.Beer();
代替:
public Malt.Beer Beer = new Malt.Beer();
它无法编译,但想知道我是不是语法错误或隐式变量 (var) 不能在此范围内使用?
最佳答案
来自MSDN programming guide对于 C#:
Remarks The following restrictions apply to implicitly-typed variable declarations: 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.
关于c# - C#中字段的隐式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32744729/