C# var 关键字有什么意义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/209199/
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
What's the point of the var keyword?
提问by Ed Guiness
The varkeyword does away with the need for an explicit type declaration and I have read with interest the SO discussionof when it might be appropriate.
该变种关键字摒弃了需要一个明确的类型声明,我有兴趣地阅读SO讨论时,它可能是适当的。
I have also read about (but not used) Boowhich seems to take things a step further by making it optional to declare a local variable. With Boo, both the type and the declaration can be implied.
我也读过(但没有使用过)Boo,它似乎更进了一步,将声明局部变量设为可选。使用 Boo,类型和声明都可以隐含。
Which leads me to wonder, why did the C# language designers bother to include a var keyword at all?
这让我想知道,为什么 C# 语言设计者要费心去包含一个 var 关键字?
Update: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...
更新:是的,var 支持匿名类型,但匿名类型本身不需要 var 关键字...
var anon = new { Name = "Terry", Age = 34 };
versus
相对
anon = new { Name = "Terry", Age = 34 };
采纳答案by JSB????
Update:There are two related questions here, actually: 1. Why do I have to declare variables at all? 2. What use is "var" in a language that makes you declare variables?
更新:这里有两个相关的问题,实际上: 1. 为什么我必须声明变量?2. 在让你声明变量的语言中,“var”有什么用?
The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:
(1) 的答案很多,可以在其他地方找到该问题的答案。我对(2)的回答如下:
As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:
正如其他评论者所说,LINQ 将其用于匿名类型。然而,LINQ 实际上是一个更普遍的问题的实例,其中表达式右侧的类型或者程序员不知道,或者非常冗长。考虑:
SomeGeneric<VeryLongTypename<NestedTypename>> thing = new
SomeGeneric<VeryLongTypename<NestedTypename>>();
Verbose and error-prone, right? So now they let you do this:
冗长且容易出错,对吧?所以现在他们让你这样做:
var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();
By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.
通过减少信息的重复,消除了错误。请注意,这里不只是打字错误:左手表达式的类型有可能被错误打字,编译器可以默默地从左到右强制转换,但转换实际上丢失了右值。当右值返回的类型可能未知或匿名时,这一点更为重要。
回答by DOK
I believe that var (and several other new keywords) were added specifically to support Linq.
我相信 var(和其他几个新关键字)是专门添加来支持 Linq 的。
var is the keyword used to create an anonymous type - see http://msdn.microsoft.com/en-us/library/bb397696.aspx
var 是用于创建匿名类型的关键字 - 请参阅http://msdn.microsoft.com/en-us/library/bb397696.aspx
Anonymous types can be used in other places than Linq.
匿名类型可以在 Linq 以外的其他地方使用。
var is exceedingy useful for Linq. In fact, according to one expert author, "Without ‘var', LINQ gets too painful to use."
var 对 Linq 非常有用。事实上,根据一位专家作者的说法,“如果没有 'var',LINQ 使用起来会很痛苦。”
回答by BlackWasp
For anonymous types, which amongst other things support LINQ.
对于匿名类型,其中包括支持 LINQ。
回答by Ferruccio
Without the var keyword it becomes possible to accidentally create a new variable when you had actually intended to use an already existing variable. e.g.
如果没有 var 关键字,当您实际上打算使用已经存在的变量时,可能会意外创建一个新变量。例如
name = "fred";
...
Name = "barney"; // whoops! we meant to reuse name
回答by Jason Hymanson
This is a bit subjective, but I think designing C# 3.0 to have the "var" keyword for implicitly typed variables instead of no keyword makes the code more readable. For example, the first code block below is more readable than the second:
这有点主观,但我认为将 C# 3.0 设计为对隐式类型变量使用“var”关键字而不是没有关键字会使代码更具可读性。例如,下面的第一个代码块比第二个更具可读性:
Obvious where the variable is declared:
变量声明的位置很明显:
var myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;
Not obvious where the variable is declared:
声明变量的位置并不明显:
myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;
These are over-simplistic examples. I think you can see where this goes. In complex situations it might be nice to be able to find the place where a variable is actually defined.
这些都是过于简单化的例子。我想你可以看到这是怎么回事。在复杂的情况下,能够找到实际定义变量的位置可能会很好。
回答by Bill K
disclaimer: my examples are Java because that's what I know, but the concepts should be identical.
免责声明:我的示例是 Java,因为这是我所知道的,但概念应该是相同的。
I voted up the answer that I feel is critical (it's too easy to accidentally create a new variable).
我投票赞成我认为至关重要的答案(意外创建新变量太容易了)。
bill=5;
bi11=bill+5
What's the value of bill?
票据的价值是多少?
That said, I find it somewhat irritating at times to type:
也就是说,我发现有时输入以下内容有点烦人:
DataOutputStream ds=new DataOutputStream();
Seems redundant, but honestly there is nothing really wrong with it. It does not take you any longer to type it twice, and it's extremely helpful. What takes time is when you have questions--when you aren't sure just how to use some API. If it really bothers you to type that type declaration twice, then why are you wasting your time here? Since you started reading this you could have typed 30 or 40 declaration, enough for every declaration you'll need for the next two weeks.
似乎多余,但老实说,它并没有什么问题。您不再需要输入两次,而且非常有帮助。需要时间的是当您有疑问时——当您不确定如何使用某些 API 时。如果您真的很困扰键入该类型声明两次,那么您为什么要在这里浪费时间?自从您开始阅读本文后,您可能已经输入了 30 或 40 份声明,足以满足接下来两周所需的每份声明。
I guess I'm saying that although I understand the emotional stress that repeating yourself can cause, the consistency, clarity and ability to make more intelligent tools makes it WELL worth while.
我想我是说,虽然我理解重复自己可能导致的情绪压力,但一致性、清晰度和制作更智能工具的能力使它非常值得。
One more thing, MOST of the time the code should not be like my example above. What you should be doing is this:
还有一件事,大多数时候代码不应该像我上面的例子。你应该做的是:
DataOutput ds=new DataOutputStream();
This immediately hides the fact that you are using a concrete class into a template. That template should be able to do all the operations you need on your class. Later if you wanted to replace ds with some other kind of output stream, simply changing that single line will fix it. If you were using the features not available to DataOutput by casting to DataOutputStream, the editor will easily figure it out and let you know.
这立即隐藏了您在模板中使用具体类的事实。该模板应该能够执行您在类上所需的所有操作。稍后,如果您想用某种其他类型的输出流替换 ds,只需更改该单行即可修复它。如果您通过转换为 DataOutputStream 使用了 DataOutput 不可用的功能,编辑器会很容易地找出来并让您知道。
回答by Joel Coehoorn
In your question, var
adds value to the code by telling the compiler the word anon
is now legal for use anywhere you'd expect to see an item of the type implied in the assignment. Requiring the introduction of names to the compiler like this allows the compiler to reject things it hasn't been explicitly told are allowed, and thereby catch certain kinds of errors at compile time so they don't blow up at runtime.
在您的问题中,var
通过告诉编译器该词anon
现在可以在您希望看到赋值中隐含类型的项目的任何地方使用合法,从而为代码增加价值。像这样要求向编译器引入名称允许编译器拒绝它没有被明确告知被允许的东西,从而在编译时捕获某些类型的错误,这样它们就不会在运行时爆炸。
For example, in the update section of your question, you asked about this snippet:
例如,在您问题的更新部分,您询问了以下代码段:
anon = new { Name = "Terry", Age = 34 };
The problem with allowing it this way is that it turns anything on the left hand side of any assignment where the name didn't previously exist into a variable declaration, even if it's a really a typo. If later in the program you assign something else to anon and then even further on reference the new value, but the middle statement had a typo, you've got a problem that won't show up until runtime.
以这种方式允许它的问题在于,它会将名称以前不存在的任何赋值左侧的任何内容转换为变量声明,即使它确实是一个错字。如果稍后在程序中将其他内容分配给 anon,然后进一步引用新值,但中间语句有错字,则您遇到了直到运行时才会出现的问题。
Your response is that Boo does it, so it must be okay or at least possible. But that's a red herring. We're talking about C#, not Boo. One of the purposes of C# is to have a language where the compiler can catch as many errors as possible. Boo wants to do that, too, but it also wants be more like Python. So it sacrifices some(not all) of C#'s compile-time safety in exchange for python-like syntax.
你的回答是 Boo 做到了,所以它一定没问题,或者至少是可能的。但这是一条红鲱鱼。我们谈论的是 C#,而不是 Boo。C# 的一个目的是拥有一种编译器可以捕获尽可能多的错误的语言。Boo 也想这样做,但它也想更像 Python。所以它牺牲了一些(不是全部)C# 的编译时安全性来换取类似 python 的语法。
回答by Kelsey
I understand the need for var and it serves it purpose great. Having no keyword and just defining variables on the fly with no type is scary. Your hurting the next guy who has to maintain your code or yourself if you need to rework the code you haven't touched in over a year. I am not sure that is a door that should be opened in C# and I hope it isn't as var is already causing readability issues when being over used when it is not necessary.
我理解对 var 的需求,它的用途很好。没有关键字并且只是在没有类型的情况下动态定义变量是可怕的。如果您需要重新编写一年多没有接触过的代码,那么您会伤害下一个必须维护您的代码的人或您自己。我不确定这是一扇应该在 C# 中打开的门,我希望它不是因为 var 在不必要时过度使用时已经导致可读性问题。
Almost every .net 3.5 example I am seeing lately has all variables defined with var.
我最近看到的几乎每个 .net 3.5 示例都使用 var 定义了所有变量。
The arguement I make is that it really sacrifices readability for the sake of saving keystrokes when it is over used. For example:
我的论点是,当它被过度使用时,为了节省击键次数,它确实牺牲了可读性。例如:
// What myVar is, is obvious
SomeObject myVar = new SomeObject();
// What myVar is, is obvious here as well
var myVar = new SomeObject();
The problem I see is that people are using it everywhere... for example:
我看到的问题是人们到处都在使用它……例如:
// WTF is var without really knowing what GetData() returns?
// Now the var shortcut is making me look somewhere else when this should
// just be readable!
var myVar = GetData();
// If the developer would have just done it explicitly it would actually
// be easily readable.
SomeObject myVar = GetData();
So the next arguement will be, just name the function better...
所以下一个争论将是,只是更好地命名函数......
var weight = GetExactWeightOfTheBrownYakInKilograms();
Still don't know what is coming back. Is it an int, decimal, float, weight object, what? I still have to waste time looking it up... need the intellisense crutch to save the day from my lazy programming. Maybe include the return type in the function name. Good idea, now using var has saved us nothing except making all my functions have real long names.
还不知道什么回来。它是一个 int、decimal、float、weight 对象,什么?我仍然需要浪费时间查找它...需要智能感知拐杖来从我懒惰的编程中拯救一天。可能在函数名称中包含返回类型。好主意,现在使用 var 对我们没有任何帮助,除了让我的所有函数都有真正的长名称。
I think people are just over using var and it is leading to lazy programming which in turn leads to harder to read code. Everytime you type out the keyword var, you should have a good reason why you are using it instead of being explicit.
我认为人们刚刚过度使用 var,它导致懒惰的编程,从而导致更难阅读代码。每次输入关键字 var 时,您都应该有充分的理由使用它而不是显式地使用它。