问题描述
还有一个原因,为什么我不能做到以下几点:
Is there a reason why I can't do the following:
foreach (var Item in DataTable.Rows) {
,而不必做
foreach (DataRow Item in DataTable.Rows) {
我还以为这是可能的,就像它在其它数据类型。例如:
I would have thought this was possible, like it is on other datatypes. For example:
foreach (var Employee in Staff) { // string[] Staff etc...
当我尝试的第一个foreach循环,我得到了错误的 CS0021:无法应用索引与[]以类型的前pression对象
When I try the first foreach loop, I get the the error CS0021: Cannot apply indexing with [] to an expression of type 'object'.
为什么不能编译器弄清楚,.Rows返回数据行的集合?
Why can't the compiler figure out that .Rows returns a collections of DataRows?
推荐答案
行
有效地返回的IEnumerable
( DataRowCollection
),因此编译器只能挑对象
作为类型 VAR
。使用 Rows.Cast< DataRow的>
如果你想使用 VAR
。
Rows
effectively returns IEnumerable
(DataRowCollection
), so the compiler can only pick object
as the type for var
. Use Rows.Cast<DataRow>
if you want to use var
.
铸造
可枚举,所以你必须包括System.Linq的。
Cast
is defined on Enumerable, so you have to include System.Linq.
这篇关于为什么我不能做的foreach(在DataTable.Rows VAR项)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!