什么是var关键字的地步? [英] What's the point of the var keyword?

查看:143
本文介绍了什么是var关键字的地步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助 VAR 关键字摒弃了需要明确的类型声明,我已阅读感兴趣的所以当它可能是适当的讨论

我也读到(但不使用)这似乎通过进一步采取了一步<一个HREF =HTTP://boo.$c$chaus.org/Type+Inference>可选的声明一个局部变量。随着嘘,无论是类型和声明可以被暗示。

这使我想知道,为什么C#语言的设计者懒得包括var关键字呢?

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

  VAR匿名=新的{名称=特里,年龄= 34};

 匿名=新的{名称=特里,年龄= 34};


解决方案

更新:有两个相关的问题在这里,实际上是:
1.为什么我必须在所有声明变量?
2.有什么用VAR中,让你声明变量的语言?

要的答案(1)很多,而且可以为其他地方这个问题被发现。我的回答(2)如下:

至于其他评论者所说,LINQ使用此为它的匿名类型。然而,LINQ实际上是一个更一般的问题,其中一个前pression的右手边的类型是未知的程序员,或者是非常冗长的一个实例。试想一下:

  SomeGeneric&LT; VeryLongTypename&LT; NestedTypename&GT;&GT;事情=新
SomeGeneric&LT; VeryLongTypename&LT; NestedTypename&GT;&GT;();

繁琐,容易出错的,对不对?所以,现在他们让你这样做:

  VAR的事情=新SomeGeneric&LT; VeryLongTypename&LT; NestedTypename&GT;&GT;();

通过减少信息的复制,误差被消除。请注意,不只是打字错误,此处有可能为左手前pression以这样的方式编译器可以默默地从左至右投中拼写错误的类型,但中投实际损失右值的某些属性。这是更重要的,当由右值返回的类型可能是未知的或匿名的。

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 };

解决方案

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.

这篇关于什么是var关键字的地步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆