为什么var会是坏事? [英] Why would var be a bad thing?

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

问题描述

我一直和我的同事聊天,听说他们的编码标准明确禁止他们使用C#中的 var 关键字。他们不知道为什么是这样的,我总是发现隐式声明在编码时非常有用。我从来没有找到什么类型的变量是什么问题(你只能将鼠标悬停在VS中的变量,你会得到类型的方式)。



任何人都知道为什么在C#中使用var关键字是个不好的主意。

解决方案

。Net Framework Design Guidelines (awesome book)于2008年11月推出,建议考虑使用<$ c $



另一方面,如果使用 var 将导致阅读代码时的歧义,正如Anton Gogolev指出的那样,那么最好不要使用它。



,他们实际上给出了这个例子:

  var names = new List< string>(); //好用的var 

string source = GetSource();
var tokens = source.Split(''); // 好;大多数开发人员知道String.Split

var id = GetId(); //可能不好;不清楚ID的类型是什么

这可能是为了确保可读性不受你的组织决定你不值得 var 并禁止它。

这是一个耻辱,但它是一个耻辱,



在大多数情况下,使用 var 进行简单操作类型实际上有助于可读性,我们不能忘记使用 var 也没有性能损失。


I've been chatting with my colleagues the other day and heard that their coding standard explicitly forbids them to use the var keyword in C#. They had no idea why it was so and I've always found implicit declaration to be incredibly useful when coding. I've never had any problems finding out what type the variable was (you only hover over the variable in VS and you'll get the type that way).

Does anyone know why it would be a bad idea to use the var keyword in C#?

解决方案

The writers of the .Net Framework Design Guidelines (awesome book) that came out in November 2008 recommend considering using var when the Type is obvious and unambiguous.

On the other hand, if using var would result in an ambiguity when reading the code, as Anton Gogolev pointed out, then it's better not to use it.

in the book (Annex A), they actually give this example:

var names = new List<string>(); // good usage of var

string source = GetSource();
var tokens = source.Split(' '); // ok; most developers know String.Split

var id = GetId(); // Probably not good; it's not clear what the type of id is

It's possible that, to ensure that readability is not subjected to the whims of lowly developers, your organisation has decided that you were not worthy of var and banned it.
It's a shame though, it's like having a nice tool at your disposal but keeping it in a locked glass cabinet.

In most cases, using var for simple types actually helps readability and we must not forget that there is also no performance penalty for using var.

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

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