Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c# - Why does var evaluate to System.Object in "foreach (var row in table.Rows)"?

When I enter this foreach statement...

foreach (var row in table.Rows)

...the tooltip for var says class System.Object

I'm confused why it's not class System.Data.DataRow.

(In case you're wondering, yes, I have using System.Data at the top of my code file.)


If I declare the type explicitly, as in...

foreach (DataRow row in table.Rows)

...it works fine with no errors.


Also if I do...

var numbers = new int[] { 1, 2, 3 };
foreach (var number in numbers)

...var evaluates to struct System.Int32. So, the problem is not that var doesn't work in a foreach clause.


So, there's something strange about DataRowCollection where the items don't automatically evaluate to DataRow. But I can't figure out what it is. Does anyone have an explanation?


Update

I was really torn which answer to mark (Codeka and Oliver)...In the end, I decided to mark Codeka's because it truly answers my question, but Oliver answers the question I should have been asking :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because the DataRowCollection class only implements the non-generic version of IEnumerable. So the compiler doesn't know what the type of the variable is.

By explicitly putting the type in there, you basically tell the compiler to generate an explicit cast from object to DataRow.

This is a problem you'll find with many of the collections and classes added back in the .NET 1.x days, before generics were available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...