使用C#var隐式键入System.Data.Datarow [英] Use of C# var for implicit typing of System.Data.Datarow

查看:82
本文介绍了使用C#var隐式键入System.Data.Datarow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foreach (var row in table.Rows)
{
     DoSomethingWith(row);
}

假设我正在使用标准的System.Data.DataTable(具有System.Data.DataRow对象的集合),则上面的变量'row'解析为object类型,而不是System.Data.DataRow.

Assuming that I'm working with a standard System.Data.DataTable (which has a collection of System.Data.DataRow objects), the variable 'row' above resolves as an object type, not a System.Data.DataRow.

foreach (DataRow row in table.Rows)
{
     DoSomethingWith(row);
}

符合我的期望.有什么特殊原因吗?

Works as I would expect. Is there a particular reason for this?

谢谢.

推荐答案

这是因为RowsDataRowCollection,这又是IEnumerable而不是IEnumerable<DataRow>,这意味着推断的类型将是object

That's because Rows is DataRowCollection, which in turn is IEnumerable and not IEnumerable<DataRow>, which means that type inferred will be object.

当您明确声明foreach中的类型时,您会指示c#将强制类型转换添加到每个调用中,这就是它起作用的原因.

When you explicitly state type in foreach, you instruct c# to add cast to each call, which is why it works.

这篇关于使用C#var隐式键入System.Data.Datarow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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