使用C#var隐式键入System.Data.Datarow [英] Use of C# var for implicit typing of 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?
谢谢.
推荐答案
这是因为Rows
是DataRowCollection
,这又是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屋!