var 关键字有什么意义?

发布于 2024-07-08 11:26:44 字数 687 浏览 12 评论 0原文

var 关键字不需要显式类型声明,我已饶有兴趣地阅读了SO讨论何时可能合适。

我还读过(但未使用) Boo ,它似乎通过使事情更进一步声明局部变量是可选的。 对于 Boo,类型和声明都可以被隐含。

这让我想知道,为什么 C# 语言设计者要费心去包含 var 关键字?

更新:是的,var 支持匿名类型,但匿名类型本身不需要 var 关键字...

var anon = new { Name = "Terry", Age = 34 };

anon = new { Name = "Terry", Age = 34 };

The var keyword does away with the need for an explicit type declaration and I have read with interest the SO discussion of when it might be appropriate.

I have also read about (but not used) Boo which 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.

Which leads me to wonder, why did the C# language designers bother to include a var keyword at all?

Update: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...

var anon = new { Name = "Terry", Age = 34 };

versus

anon = new { Name = "Terry", Age = 34 };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

执手闯天涯 2024-07-15 11:26:44

如果没有 var 关键字,当您实际上打算使用已经存在的变量时,可能会意外创建新变量。 例如

name = "fred";
   ...
Name = "barney"; // whoops! we meant to reuse name

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.

name = "fred";
   ...
Name = "barney"; // whoops! we meant to reuse name
南薇 2024-07-15 11:26:44

更新:这里实际上有两个相关的问题:
1. 为什么我必须声明变量?
2. 在要求声明变量的语言中,“var”有什么用?

(1) 的答案有很多,可以在其他地方找到该问题的答案。 我对 (2) 的回答如下:

正如其他评论者所说,LINQ 将其用于其匿名类型。 然而,LINQ 实际上是一个更普遍问题的实例,其中表达式右侧的类型要么程序员不知道,要么极其冗长。 考虑一下:

SomeGeneric<VeryLongTypename<NestedTypename>> thing = new   
SomeGeneric<VeryLongTypename<NestedTypename>>();

冗长且容易出错,对吗? 所以现在他们让你这样做:

var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();

通过减少信息重复,消除错误。 请注意,这里不仅仅是键入错误:左侧表达式的类型可能会被错误地键入,从而使编译器可以默默地从左到右进行强制转换,但强制转换实际上会丢失该表达式的某些属性。右值。 当右值返回的类型可能未知或匿名时,这一点甚至更为重要。

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?

The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:

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:

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.

无边思念无边月 2024-07-15 11:26:44

我理解 var 的需要,它非常适合它的目的。 没有关键字并且只是动态定义没有类型的变量是可怕的。 如果您需要重新编写一年多没有碰过的代码,那么您会伤害下一个必须维护您的代码的人或您自己。 我不确定这是否应该在 C# 中打开,我希望这不是因为 var 在不必要的情况下过度使用时已经导致可读性问题。

我最近看到的几乎每个 .net 3.5 示例都使用 var 定义了所有变量。

我的观点是,当它被过度使用时,为了节省击键次数,它确实牺牲了可读性。 例如:

// What myVar is, is obvious
SomeObject myVar = new SomeObject();

// What myVar is, is obvious here as well
var myVar = new SomeObject();

我看到的问题是人们到处都在使用它...例如:

// 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();

所以下一个争论将是,只需更好地命名该函数...

var weight = GetExactWeightOfTheBrownYakInKilograms();

仍然不知道会返回什么。 它是 int、decimal、float、weight 对象还是什么? 我仍然需要浪费时间查找它......需要智能感知拐杖来拯救我懒惰的编程。 也许在函数名称中包含返回类型。 好主意,现在使用 var 除了让我的所有函数都有真正的长名称之外,没有为我们节省任何东西。

我认为人们过度使用 var,它导致了懒惰的编程,进而导致代码更难阅读。 每次你输入关键字 var 时,你都应该有一个充分的理由为什么要使用它而不是明确的。

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.

Almost every .net 3.5 example I am seeing lately has all variables defined with 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.

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.

毅然前行 2024-07-15 11:26:44

这有点主观,但我认为设计 C# 3.0 时使用“var”关键字来表示隐式类型变量,而不是没有关键字,可以使代码更具可读性。 例如,下面的第一个代码块比第二个代码块更具可读性: 声明

变量的位置明显:

var myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;

声明变量的位置不明显:

myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;

这些都是过于简单化的示例。 我想你可以看到这会发生什么。 在复杂的情况下,能够找到实际定义变量的位置可能会很好。

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:

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.

踏雪无痕 2024-07-15 11:26:44

在您的问题中, var 通过告诉编译器单词 anon 现在可以合法地在您希望看到隐含类型的项目的任何地方使用,从而为代码增加了价值分配。 像这样要求向编译器引入名称允许编译器拒绝未明确告知允许的内容,从而在编译时捕获某些类型的错误,这样它们就不会在运行时崩溃。

例如,在问题的更新部分中,您询问了以下代码片段:

anon = new { Name = "Terry", Age = 34 };

允许这种方式的问题是,它将以前不存在名称的任何赋值左侧的任何内容转换为变量声明,即使这确实是一个错字。 如果稍后在程序中您将其他内容分配给 anon,然后进一步引用新值,但中间语句有一个拼写错误,那么您会遇到一个直到运行时才会出现的问题。

你的回答是 Boo 做到了,所以它一定没问题或者至少是可能的。 但这是转移注意力的事情。 我们谈论的是 C#,而不是 Boo。 C# 的目的之一是拥有一种编译器可以捕获尽可能多的错误的语言。 Boo 也想这样做,但它也希望更像 Python。 因此,它牺牲了 C# 的一些(不是全部)编译时安全性来换取类似 Python 的语法。

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.

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.

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.

还不是爱你 2024-07-15 11:26:44

免责声明:我的示例是 Java,因为这是我所知道的,但概念应该是相同的。

我投票赞成了我认为至关重要的答案(很容易意外创建新变量)。

bill=5;
bi11=bill+5

账单的价值是多少?

也就是说,我有时觉得输入以下内容有点烦人:

DataOutputStream ds=new DataOutputStream();

似乎多余,但说实话,这并没有什么问题。 您不再需要输入两次,而且非常有帮助。 需要时间的是当您有疑问时——当您不确定如何使用某些 API 时。 如果两次键入该类型声明确实让您感到困扰,那么为什么还要在这里浪费时间呢? 自从您开始阅读本文以来,您可能已经输入了 30 或 40 份声明,足以满足您接下来两周所需的每份声明。

我想我是说,虽然我理解重复自己可能会造成的情绪压力,但一致性、清晰度和制造更智能工具的能力使其非常值得。

还有一件事,大多数时候代码不应该像我上面的例子一样。 您应该做的是:

DataOutput ds=new DataOutputStream();

这立即隐藏了您正在模板中使用具体类的事实。 该模板应该能够执行您的类所需的所有操作。 稍后,如果您想用其他类型的输出流替换 ds,只需更改该行即可修复它。 如果您通过转换为 DataOutputStream 使用了 DataOutput 不可用的功能,编辑器将轻松找出并让您知道。

disclaimer: my examples are Java because that's what I know, but the concepts should be identical.

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.

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.

So要识趣 2024-07-15 11:26:44

我相信 var (以及其他几个新关键字)是专门添加来支持 Linq 的。

var 是用于创建匿名类型的关键字 - 请参阅 http://msdn。 microsoft.com/en-us/library/bb397696.aspx

匿名类型可以用在 Linq 以外的其他地方。

var 对于 Linq 非常有用。 事实上,根据一位专家作者的说法,“如果没有 'var',LINQ 使用起来会很痛苦。"

I believe that var (and several other new keywords) were added specifically to support Linq.

var is the keyword used to create an anonymous type - see http://msdn.microsoft.com/en-us/library/bb397696.aspx

Anonymous types can be used in other places than Linq.

var is exceedingy useful for Linq. In fact, according to one expert author, "Without ‘var’, LINQ gets too painful to use."

听风念你 2024-07-15 11:26:44

有时类型相当大。 想象一下,您有一个字典,其中字典中包含泛型类型。 var 将使这个更具可读性。
这也是一种编码实践。

另外,如果你想创建像 var randomData = { Id = 1, name = "Amit" } 这样的匿名类型,

我个人使用类型,因为有时你需要知道函数返回什么(如果你想将结果传递给其他一些功能。)。 与将光标悬停在 var 上相比,查看类型更容易。
例如: var result = GetSomethign();

另外,有时您需要按 F12 导航到类型。 这对于 var 来说是不可能的。 当您处于调试模式时,这有点令人恼火,因为您在调试时看不到类型。 您需要停止调试,查看类型并再次开始调试。

Sometimes the type is pretty big. Imagine the type where you have a dictionary with generic type inside a dictionary. var will make this much more readable.
Its also a coding practise.

Also, in case you want to create anonymous types like var randomData = { Id = 1, name = "Amit" }

I personally use types because sometimes you need to know what the function returns(In case, you want to pass the result to some other function.). Its easier to see the type than to hover the cursor on var.
For eg: var result = GetSomethign();

Also, sometimes you need to navigate to the type pressing F12. This is not possible with var. This is a little irritating when you are in debugging mode because you cannot see the type while debugging. You need to stop debugging, see the type and start debugging again.

自演自醉 2024-07-15 11:26:44

对于匿名类型,其中之一支持 LINQ。

http://www.blackwasp.co.uk/CSharpAnonTypes.aspx

For anonymous types, which amongst other things support LINQ.

http://www.blackwasp.co.uk/CSharpAnonTypes.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文