在方法之外使用 var
我想使用 var 关键字在我的类中声明一个字段,但是 var 似乎只能在方法内部工作。
我的代码看起来像:
public static Dictionary<string, string> CommandList = new Dictionary<string, string>{};
我想要:
public static var CommandList = new Dictionary<string, string>
为什么这不可能?
I wanted to use the var
keyword to declare a field in my class however var
only seems to work inside methods.
The code I have looks like:
public static Dictionary<string, string> CommandList = new Dictionary<string, string>{};
and I wanted to have:
public static var CommandList = new Dictionary<string, string>
How come this isn't possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我关于这个主题的文章:
为什么不var on fields?
总结一下:
如果我们有“var”字段,那么在分析表达式之前无法确定字段的类型,而这发生在我们已经需要知道字段的类型之后.
如果这些引用中有长链,甚至循环怎么办?所有这些算法都必须在一个顶级类型信息从确定而不是被它们消耗的世界中进行重写和测试。
如果您有“var”字段,则初始值设定项可能是匿名类型。假设该字段是公共的。 CLR 或 CLS 中还没有任何关于公开匿名类型字段的正确方法的标准。
My article on the subject:
Why no var on fields?
To summarize:
If we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.
What if there are long chains, or even cycles in those references? All of those algorithms would have to be rewritten and tested in a world where top-level type information is being determined from them rather than being consumed by them.
If you have "var" fields then the initializer could be of anonymous type. Suppose the field is public. There is not yet any standard in the CLR or the CLS about what the right way to expose a field of anonymous type is.
来自 C# 参考
在方法范围内声明
可以有一个隐式类型 var。
同样来自 C# 编程参考
它只是不适合您想要的用途。
它的主要目标是允许在代码中支持匿名类型,并具有允许以简洁的方式指定局部变量的额外优点。
From the C# reference
that are declared at method scope
can have an implicit type var.
Also from The C# Programming Reference
It just isn't intended for the usage you have in mind.
It's primary aim is to allow the support of anonymous types in your code, with the added advantage of allowing a nice terse way of specifying local variables.
简短的回答是因为规范说这是不合法的。 ;-)
一般来说,无论如何这都不是您想要做的。成员的类型应为
IDictionary
而不是Dictionary
。这是一个小问题,但通常最好在外部可见对象中使用接口,这样您就可以稍后更改类型而不会影响代码的客户端。编译器只是给你一点小小的推动来引导你这个方向。The short answer is because the spec says it's not legal. ;-)
Generally, this is not what you want to do anyway. The type of the member should be
IDictionary<string, string>
notDictionary<string, string>
. It's a small nit but generally it's better to use an interface in an externally visible object so you can change the type later without affecting the clients of the code. The compiler is just giving you a little nudge to guide you that direction.