C#中var关键字的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of var keyword in C#
提问by ljs
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
在与同事讨论了 C# 3 中“var”关键字的使用之后,我想知道人们对通过 var 进行类型推断的适当使用有何看法?
For example I rather lazily used var in questionable circumstances, e.g.:-
例如,我在有问题的情况下懒惰地使用 var,例如:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
更合法的 var 用法如下:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
有趣的是,LINQ 似乎有点灰色地带,例如:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
很明显,它将是一个实现 IEnumerable 的类型,结果是什么,但是它并不像声明一个新对象的 var 那样完全明显。
It's even worse when it comes to LINQ to objects, e.g.:-
当涉及到 LINQ 对象时,情况更糟,例如:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
这并不比等效的 foreach(var item in someList) { // ... } 等效。
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
这里有一个关于类型安全的真正问题——例如,如果我们将该查询的结果放入一个接受 IEnumerable<int> 和 IEnumerable<double> 的重载方法中,调用者可能会无意中传入错误的类型。
var
doesmaintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
var
确实保持强类型化,但问题是类型在定义中不立即显现是否危险,当重载意味着当您无意中将错误类型传递给方法时可能不会发出编译器错误时,这种情况会被放大。
采纳答案by Matt Hamilton
I still think var
can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:
我仍然认为var
在某些情况下可以使代码更具可读性。如果我有一个带有 Orders 属性的 Customer 类,并且我想将它分配给一个变量,我将这样做:
var orders = cust.Orders;
I don't care if Customer.Orders is IEnumerable<Order>
, ObservableCollection<Order>
or BindingList<Order>
- all I want is to keep that list in memory to iterate over it or get its count or something later on.
我不在乎 Customer.Orders 是IEnumerable<Order>
,ObservableCollection<Order>
还是BindingList<Order>
- 我想要的只是将该列表保留在内存中以对其进行迭代或获取其计数或其他内容。
Contrast the above declaration with:
将上述声明与:
ObservableCollection<Order> orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order>
to IList<Order>
) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
对我来说,类型名称只是噪音。如果我返回并决定更改 Customer.Orders 的类型(比如 from ObservableCollection<Order>
to IList<Order>
),那么我也需要更改该声明 - 如果我在第一个使用 var ,我就不必这样做地方。
回答by Matt Hamilton
I think the use of var should be coupled with wisely-chosen variable names.
我认为 var 的使用应该与明智选择的变量名称相结合。
I have no problem using var in a foreach statement, provided it's not like this:
我在 foreach 语句中使用 var 没有问题,前提是它不是这样的:
foreach (var c in list) { ... }
If it were more like this:
如果它更像这样:
foreach (var customer in list) { ... }
... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.
...那么阅读代码的人更有可能理解“列表”是什么。如果您可以控制列表变量本身的名称,那就更好了。
The same can apply to other situations. This is pretty useless:
这同样适用于其他情况。这是非常无用的:
var x = SaveFoo(foo);
... but this makes sense:
...但这是有道理的:
var saveSucceeded = SaveFoo(foo);
Each to his own, I guess. I've found myself doing this, which is just insane:
我猜每个人都有自己的。我发现自己这样做了,这太疯狂了:
var f = (float)3;
I need some sort of 12-step var program. My name is Matt, and I (ab)use var.
我需要某种 12 步 var 程序。我的名字是马特,我(ab)使用 var。
回答by Jon Limjap
In our office, our CTO has categorically banned the use of the var keyword, for the same reasons that you have stated.
在我们的办公室,我们的 CTO 已明确禁止使用 var 关键字,原因与您陈述的相同。
Personally I find the use of var only valid in new object declarations, since the type of the object is obvious in the statement itself.
我个人认为 var 的使用只在新的对象声明中有效,因为对象的类型在语句本身中是显而易见的。
For LINQ queries, you can resolve results to:
对于 LINQ 查询,您可以将结果解析为:
IEnumerable<TypeReturnedBySelectObject>
回答by aku
I had the same concern when I started to use varkeyword.
However I got used to it over time and not going to go back to explicit variable types.
Visual Studio's compiler\intellisense are doing a very good job on making work with implicitly typed variables much easier.
当我开始使用var关键字时,我也有同样的担忧。
然而,随着时间的推移,我已经习惯了它,并且不会回到显式变量类型。Visual Studio 的编译器\智能感知在使隐式类型变量的使用变得更加容易方面做得非常好。
I think that following proper naming conventions can help you to understand code much better then explicit typing.
我认为遵循正确的命名约定可以帮助您比显式键入更好地理解代码。
It seems to be same sort of questions like "shoud I use prefixes in variable names?".
Stick with good variable names and let the compiler think on variable types.
这似乎是类似“我应该在变量名中使用前缀吗?”之类的问题。
坚持使用好的变量名,让编译器考虑变量类型。
回答by erlando
Someone doesn't like criticism of var.. All answers downmodded.. oh well..
有人不喜欢对 var 的批评.. 所有的答案都被修改了.. 哦,好吧..
@Jon Limjap: I know. :) What I meant was that the readability is degraded like it is in VB6. I don't like to rely on Intellisense to figure out what type a given variable is. I want to be able to figure it out using the source alone.
@Jon Limjap:我知道。:) 我的意思是可读性降低了,就像在 VB6 中一样。我不喜欢依靠 Intellisense 来确定给定变量的类型。我希望能够单独使用源来弄清楚。
Naming conventions doesn't help either - I already use good names. Are we going back to prefixing?
命名约定也无济于事 - 我已经使用了好名字。我们要回到前缀吗?
回答by Murph
I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).
我认为 VAR 的关键是只在适当的时候使用它,即在 Linq 中做它促进的事情时(可能在其他情况下)。
If you've gota type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).
如果你有一个类型,那么你应该使用它 - 不这样做是简单的懒惰(与通常鼓励的创造性懒惰相反 - 优秀的程序员通常非常努力地懒惰并且可以被考虑首先是事物的来源)。
A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.
全面禁止与滥用结构一样糟糕,但确实需要一个合理的编码标准。
The other thing to remember is that its not a VB type var in that it can't change types - it isa strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).
要记住的另一件事是它不是 VB 类型变量,因为它不能改变类型 - 它是一个强类型变量,它只是推断类型(这就是为什么有人会争辩说它不是不合理的例如,在 foreach 中使用它,但出于可读性和可维护性的原因,我不同意)。
I suspect this one is going to run and run (-:
我怀疑这个会运行和运行 (-:
Murph
墨菲
回答by Jon Limjap
One specific case where var is difficult: offline code reviews, especially the ones done on paper.
var 困难的一种特殊情况:离线代码审查,尤其是在纸上完成的代码审查。
You can't rely on mouse-overs for that.
你不能依赖鼠标悬停。
回答by aku
@erlando, out of curiosity, why do you need to know the variable's type looking at the source code?
@erlando,出于好奇,为什么您需要在查看源代码时知道变量的类型?
In my practice I found that variable type is matter for me only at the time I'm using it in the code.
在我的实践中,我发现变量类型只有在我在代码中使用它时才对我很重要。
If I'm trying to do some inappropriate operation on someVarcompiler gladly gives me an error\warning.
如果我试图在someVar编译器上做一些不适当的操作,很高兴给我一个错误\警告。
I really don't care what type someVarhas if I understand whyit's being used it the given context.
如果我理解为什么在给定的上下文中使用它,我真的不在乎someVar有什么类型。
回答by Konrad Rudolph
I use var
extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.
我var
广泛使用。有人批评这会降低代码的可读性,但没有论据支持这种说法。
Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically notinterested in the type a variable has. var
takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”
诚然,这可能意味着不清楚我们正在处理什么类型。所以呢?这实际上是解耦设计的要点。在处理接口时,您显然对变量的类型不感兴趣。var
借此更进一步,真实的,但我认为争论依然从一个可读性一点是相同的:程序员不应实际感兴趣的变量的类型,而是在什么变数呢。这就是为什么微软也将类型推断称为“鸭子类型”。
So, what does a variable do when I declare it using var
? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.
那么,当我使用 声明变量时,它会做什么var
?很简单,它会执行 IntelliSense 告诉我的任何操作。任何忽略 IDE 的关于 C# 的推理都不符合现实。实际上,每个 C# 代码都是在支持 IntelliSense 的 IDE 中编写的。
If I am using a var
declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var
is not the cause, it only makes the symptoms visible. Don't blame the messenger.
如果我正在使用一个var
声明的变量并且对变量的用途感到困惑,那么我的代码就存在根本性的错误。var
不是原因,它只会使症状可见。不要责怪使者。
Now, the C# team has released a coding guideline stating that var
should onlybe used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var
). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)
现在,C# 团队发布了一个编码指南,声明它var
应该只用于捕获创建匿名类型的 LINQ 语句的结果(因为在这里,我们没有真正的替代方法var
)。好吧,搞砸了。只要 C# 团队不为我提供该指南的合理论证,我就会忽略它,因为在我的专业和个人看来,它纯粹是胡说八道。(抱歉;我没有相关指南的链接。)
Actually, there are some (superficially) good explanationson why you shouldn't use var
but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var
makes it hard to search for places where MyType
is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
实际上,对于为什么不应该使用有一些(表面上)很好的解释,var
但我仍然认为它们在很大程度上是错误的。以“可搜索性”为例:作者声称这var
使得搜索使用的地方变得困难MyType
。对。接口也是如此。实际上,我为什么想知道类在哪里使用?我可能对它在哪里实例化更感兴趣,这仍然是可搜索的,因为必须在某处调用其构造函数(即使这是间接完成的,也必须在某处提及类型名称)。
回答by erlando
@aku: One example is code reviews. Another example is refactoring scenarios.
@aku:一个例子是代码审查。另一个例子是重构场景。
Basically I don't want to go type-hunting with my mouse. It might not be available.
基本上我不想用我的鼠标去打字。它可能不可用。