利与弊.NET 3.5中var数据类型的缺点 [英] Pros & Cons of var datatype in .net 3.5

查看:207
本文介绍了利与弊.NET 3.5中var数据类型的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
在C#中使用var关键字
对"var"的使用输入变量声明

Possible Duplicates:
Use of var keyword in C#
Use of “var” type in variable declaration

大家好,

各种键操作都需要显式地进行类型转换.在可能的情况下,避免装箱和拆箱值类型."

"Var keywork it require explicitly type casting Avoid boxing and unboxing value types where possible."

是否建议使用var关键字而不是显式数据类型?

Is it advisable to use var keyword instead of explicit datatype?

推荐答案

来自

  1. 它可以更好地命名局部变量.当您读取具有显式类型的局部变量声明时,可以在以下位置获得更多信息: 那一刻,诸如"IUnitTestElement current"之类的东西很有道理. 但是,稍后使用此局部变量时,您将读取当前" 这需要一些时间才能弄清楚其含义.使用"var currentElement"可让您在任何地方都更容易阅读.

  1. It induces better naming for local variables. When you read local variable declaration with explicit type, you have more information at that moment and something like "IUnitTestElement current" makes sense. However, when this local variable is used later, you read "current" which takes some time to figure out the meaning. Using "var currentElement" makes it easier to read at any place.

它产生更好的API.当让编译器根据方法的返回类型或属性类型推断类型时,您必须在 第一名.如果您在输入中没有明确的类型 初始化表达式,您必须为成员使用最佳名称.

It induces better API. When you let compiler deduce type from method return type or property type, you have to have good types in the first place. When you don't have explicit type in the initialization expression, you have to have best names for members.

它引发变量初始化.在声明中初始化变量通常是一个好习惯,编译器需要 初始化程序,以推断用"var"声明的局部变量的类型 关键字.

It induces variable initialization. It is generally a good practice to initialize variable in the declaration, and compiler needs initializer to infer type for local variable declared with "var" keyword.

它消除了代码噪声.在很多情况下,当隐式键入local会减少开发人员需要阅读的文本量,或者 宁愿跳过.从新对象表达式中声明局部变量,或者 如果我们不使用"var",则强制转换表达式需要两次指定类型. 使用泛型,可能会导致很多其他冗余代码. 另一个示例是foreach over中的迭代变量 字典.

It removes code noise. There are a lot of cases, when implicitly typed local will reduce amount of text developer needs to read, or rather skip. Declaring local variable from new object expression or cast expression requires specifying type twice, if we don't use "var". With generics it can lead to a lot of otherwise redundant code. Another example would be iteration variable in foreach over Dictionary.

它不需要使用指令.使用var时,您无需显式引用类型,因为编译器会为您推断类型,因此您 当您需要一个临时变量时,不需要导入名称空间.

It doesn't require using directive. With var, you don't have explicit reference to type, as compiler infers type for you, so you don't need to import namespace when you need a temporary variable.

缺点可能是可读性较低的代码.例如线 int myInt = 0; 对于大多数人而言,它仍然比 var myInt = 0; 但这主要是由于我们多年来一直在研究的语法.

The cons are potentially less readable code. For instance the line int myInt = 0; is still more straightforward for most than var myInt = 0; but this is mainly due to the syntax we're all been looking at for years.

这篇关于利与弊.NET 3.5中var数据类型的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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