" VAR"在C#中的类型推断 [英] "var" type inference in C#

查看:193
本文介绍了" VAR"在C#中的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/2786727/why-does-var-evaluate-to-system-object-in-foreach-var-row-in-table-rows">Why并变种评估,以System.Object中的&ldquo;的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.

这篇关于&QUOT; VAR&QUOT;在C#中的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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