在与同事讨论了c# 3中var关键字的使用后,我想知道人们对通过var适当使用类型推断的看法是什么?

例如,我很懒地在有问题的情况下使用var,例如:-

foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.

var更合法的用法如下:-

var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.

有趣的是,LINQ似乎是一个灰色区域,例如:-

var results = from r in dataContext.SomeTable
              select r; // Not *entirely clear* what results will be here.

结果很明显,因为它将是一个实现IEnumerable的类型,但它并不完全明显,与var声明一个新对象的方式相同。

当涉及到对象的LINQ时,情况就更糟了,例如:-

var results = from item in someList
              where item != 3
              select item;

这并不比等价的foreach(var item in someList){//…}相当于。

这里有一个关于类型安全的真正问题——例如,如果我们将该查询的结果放在一个接受IEnumerable<int>和IEnumerable<double>的重载方法中,调用者可能会无意中传入错误的类型。

Var确实保持强类型,但问题是,在定义中不立即显示类型是否危险,当重载意味着当你无意中将错误的类型传递给方法时,编译器可能不会发出错误,这种情况会被放大。


当前回答

来自Essential LINQ:

除非绝对必要,否则最好不要显式声明范围变量的类型。例如,下面的代码编译干净,但是编译器可以在没有正式声明的情况下推断出类型:

List<string> list = new List<string> { "LINQ", "query", "adventure" };
var query = from string word in list
      where word.Contains("r")
      orderby word ascending
      select word;

显式声明range变量的类型会强制对LINQ Cast操作符进行幕后调用。此调用可能会产生意想不到的结果,并可能会损害性能。如果您在LINQ查询中遇到性能问题,像这里所示的强制转换可能是开始寻找罪魁祸首的一个地方。(此规则的一个例外是当您使用非泛型Enumerable时,在这种情况下您应该使用强制转换。)

其他回答

令人惊讶的是,到目前为止还没有注意到这一点,但对foreach循环变量使用var是常识。

如果您指定了特定的类型,则可能会有编译器无声地将运行时强制转换插入程序的风险!

foreach (Derived d in listOfBase)
{

上面的代码将被编译。但是编译器会插入一个从Base到Derived的向下转换。因此,如果列表中的任何内容在运行时不是派生的,则存在无效的强制转换异常。类型安全受到损害。隐形演员太可怕了。

排除这种情况的唯一方法是使用var,因此编译器会根据列表的静态类型来确定循环变量的类型。

Var,在我看来,在c#中是一个很好的东西。任何这样类型的变量仍然是强类型的,但是它从赋值函数的右边得到它的类型。因为类型信息在右侧可用,在大多数情况下,也必须在左侧输入它是不必要的和过于冗长的。我认为这在不降低类型安全性的情况下显著提高了可读性。

From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a List<T>, but you want to treat it as an IEnumerable<T> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.

Var对于匿名类型是必不可少的(正如之前对这个问题的回答之一所指出的那样)。

我会把所有其他关于宗教战争利弊的讨论归类为“宗教战争”。我的意思是对……的相对优点进行比较和讨论。

var i = 5;
int j = 5;

SomeType someType = new SomeType();
var someType = new SomeType();

...完全是主观的。

隐式类型意味着使用var关键字声明任何变量都不会在运行时造成损失,因此归根结底,这是一个关于如何让开发人员满意的争论。

Var一点也不像变量。变量仍然是强类型的,只是你不需要按下键来得到它。您可以在Visual Studio中将鼠标悬停在它上以查看类型。如果您正在阅读打印的代码,则可能需要稍微考虑一下以确定类型是什么。但是只有一行声明了它,而有很多行使用它,所以给东西起个像样的名字仍然是让你的代码更容易理解的最好方法。

使用智能感知是懒惰吗?这比输入整个名字还少。或者有些事情不那么费力,但不值得批评?我认为有,var就是其中之一。

对我来说,对var的反感说明了。net中双语的重要性。对于那些使用过VB . net的c#程序员来说,var的优势是显而易见的。标准的c#声明:

List<string> whatever = new List<string>();

在VB .NET中,相当于键入:

Dim whatever As List(Of String) = New List(Of String)

不过,在VB . net中没有人这样做。这样做是愚蠢的,因为从。net的第一个版本开始,你就可以这样做了…

Dim whatever As New List(Of String)

...它创建变量并在一个相当紧凑的行中初始化它。啊,但是如果你想要一个IList<string>,而不是一个List<string>?在VB .NET中,这意味着你必须这样做:

Dim whatever As IList(Of String) = New List(Of String)

就像你在c#中必须做的那样,显然不能使用var:

IList<string> whatever = new List<string>();

如果您需要不同的类型,它可以是。但优秀编程的基本原则之一是减少冗余,这正是var所做的。