隐式类型类成员
可能的重复:
在方法之外使用 var
我对此进行了一些搜索,但是我不太确定搜索词,所以没有找到任何东西。
为什么我不能这样做:
class foo
{
var bar = new Dictionary<string, string>();
}
猜想一定有一个很好的理由,但我想不出来!
我对推理更感兴趣,而不是因为“C# 不允许”的答案。
编辑:编辑 Dictionary
声明,抱歉(只是示例中的拼写错误)!
Possible Duplicate:
Using var outside of a method
I've searched for this a bit, but am not too sure of the search terms so didn't find anything.
Why can't i do this:
class foo
{
var bar = new Dictionary<string, string>();
}
Guessing there must be a very good reason, but i can't think of it!
I'm more interested in the reasoning, rather than the because "C# doesn't let you" answer.
EDIT: Edited Dictionary
declaration, sorry (just a typo in the example)!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
字典需要两个参数,一个键类型和一个值类型。
A dictionary needs two parameters, a key type and a value type.
“字典”是指键/值对的集合。在现实世界中,世界词典是一本包含“单词”和“定义”的书,这里“单词”是键,“定义”是值。所以很明显,在实例化
Dictionary
时不能忽略“值”。"Dictionary" means a collection of key/value pairs. In real-world, a dictionary of worlds is a book containing "Words" and "Definitions", here "Word" is key and "Definition" is value. So this is obvious that you can't ignore "value" when instantiating a
Dictionary<TKey, TValue>
.字典是一个用于将一组键映射到一组值的类,因此您需要为键和值指定类型参数。例如,如果您想根据股票代码查找股价,您可以使用:
A dictionary is a class for mapping a set of keys to a set of values, so you need to specify a type parameter for both the key and value. For example, if you want to lookup a share price based on its stock symbol, you might use:
2个原因:
所以:
至于为什么你不能这样做:
Eric Lippert 已在 博客文章。
2 reasons:
So:
As to why you cannot do this:
Eric Lippert has covered it in a blog post.
您没有指定键的类型,它应该是:
编辑:并且在类字段的情况下不允许使用“var”。
You did not specify a type for the key, it should be:
Edit: And it's not allowed to use "var" in case of class fields.