c# - C#中字段的隐式类型

标签 c# implicit-conversion

<分区>

我喜欢在 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/

相关文章:

c# - 使用 ffmpeg.autogen,从 IP 摄像机捕获视频,但未捕获音频,代码中是否缺少任何内容?

使用 shared_ptr 到 const T 的 C++ 模板实例化

c++ - 模板推导和隐式构造函数

c++ - 将枚举传递给整数类型的参数

c# - 使用转换运算符转换对象失败

c# - 将列表插入具有外键关系 Entity Framework 的多个表中

c# - MaxLength 属性不生成客户端验证属性

c# - 从任意线程调用 StateHasChanged() 是否安全?

Scala:在伴随对象中使用隐式

c# - 在 C# 中将字符串转换为 boolean 值