var 关键字有什么意义? [英] What's the point of the var keyword?

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

问题描述

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

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.

我也读过(但没有使用过)Boo 这似乎让事情更进一步进一步使其可选地声明局部变量.使用 Boo,类型和声明都可以隐含.

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.

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

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

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

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

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

对比

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

推荐答案

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

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)的回答如下:

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

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

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天全站免登陆