" VAR"在C#中的类型推断推断、类型、QUOT、VAR

2023-09-05 00:00:10 作者:万世浮华

可能重复:   Why并变种评估,以System.Object中的“的foreach(在table.Rows VAR行)和rdquo ;?

我非常惊讶于发现下面的今天......

I was rather suprised to discovered the following today....

SqlDataReader reader = cmd.ExecuteReader();
DataTable schemaTable = reader.GetSchemaTable();


// the following compiles correctly
foreach (DataRow field in schemaTable.Rows)
{
    Console.WriteLine(field["ColumnName"]);
}


// the following does not compile as 'var' is of type 'object'
foreach (var field in schemaTable.Rows)
{
    // Error: Cannot apply indexing with [] to an expression of type 'object'
    Console.WriteLine(field["ColumnName"]);
}

请告诉我怎么回事?

Whats going on here?

这是一个类型推断失败?如果是这样,是什么原因呢?

Is this a type inference failure? And if so, what causes it?

或者是它的定义的行为的一部分,或者 VAR ?如果是这样,为什么?

Or is it part of the defined behaviour or var? And if so, why?

我觉得 VAR的想法的是,你可以在任何地方的变量声明/初始化的不改变行为的

I thought the idea of var was that you could use it anywhere in a variable declaration/initialisation without changing behaviour.

推荐答案

这里的关键不是变种,但foreach循环。 foreach循环可以有选择地投迭代器除了迭代本身。

The point here is not var, but the foreach loop. The foreach loop can optionally cast the iterator in addition to iterating itself.

所以,你可以做到以下几点:

So you can do the following:

List<object> test = new List<object>();
test.Add(1);
test.Add(2);
test.Add(3);
foreach( int i in test ){
  i.Dump();
}

因此​​,即使名单类型的对象,它可以被铸造为int的在foreach里飞。

So even if the list is of type object, it can be casted to int on the fly inside the foreach.