在与同事讨论了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确实保持强类型,但问题是,在定义中不立即显示类型是否危险,当重载意味着当你无意中将错误的类型传递给方法时,编译器可能不会发出错误,这种情况会被放大。


当前回答

我想你在你的问题中指出了var的主要问题:“我不需要弄清楚类型”。正如其他人指出的那样,var是有一席之地的,但如果你不知道你正在处理的类型,你很有可能会遇到问题——不是在所有情况下,但那里有足够的气味,所以你应该怀疑。

其他回答

这两种说法都不是绝对正确的;Var对可读性既有正面影响,也有负面影响。在我看来,var应该在以下情况之一成立时使用:

类型是匿名的(好吧,这里没有任何选择,因为在这种情况下它必须是var) 根据指定的表达式,类型是明显的(即var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating())

Var没有性能影响,因为它是语法糖;一旦编译成IL,编译器就会推断出类型并定义它;没有什么动态的东西。

来自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时,在这种情况下您应该使用强制转换。)

@erlando,出于好奇,为什么你需要知道变量的类型看源代码?

在我的实践中,我发现变量类型只在我在代码中使用它的时候对我来说是重要的。

如果我试图做一些不适当的操作在某些evar编译器欣然给我一个错误\警告。

我真的不关心someVar有什么类型,如果我明白为什么它被使用在给定的上下文中。

局部变量可以被赋予一个推断的var“类型”,而不是一个显式的类型。关键字var指示编译器从初始化语句右边的表达式推断变量的类型。

// z被编译为int类型

var z = 100;

// s被编译为下面的字符串

var s = "Hello";

// a被编译为int[]

var a = new[] { 0, 1, 2 };

// expr被编译为IEnumerable //或者IQueryable

var expr =
    from c in customers
    where c.City == "London"
    select c;

// anon被编译为匿名类型

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

// list被编译为list

var list = new List<int>();

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

Var不能在类范围内的字段上使用。

使用var声明的变量不能在初始化表达式中使用。换句话说,这个表达式是合法的:int i = (i = 20);但是这个表达式会产生一个编译时错误:var I = (I = 20);

多个隐式类型变量不能在同一个语句中初始化。

如果一个名为var的类型在作用域中,那么var关键字将解析为该类型名称,并且不会被视为隐式类型局部变量声明的一部分。

将它用于匿名类型—这就是它存在的目的。其他的都是徒劳无功。像许多使用C长大的人一样,我习惯于查看类型声明的左侧。除非迫不得已,我是不会看右边的。在任何旧的声明中使用var都让我一直这样做,我个人觉得不舒服。

Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.

标准是一件好事,因为它们意味着你更有可能捡起随机代码,并能够快速地理解它。不同的东西越多,就越难。而转移到“无处不在的var”风格会有很大的不同。

I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.