开发者

What is the thinking behind having foreach cast to the variable type?

Seems like we could just have a normal statically checked assignment. I'm not sure I see the 开发者_如何学运维advantage in this case. What am I missing?


The issue here is that foreach was designed prior to generics, which didn't exist until .NET 2.0. With .NET 1.1, if you used a collection class, the IEnumerator interface's Current property always returns System.Object.

By having foreach do the cast, you could write:

foreach(string item in collection)

Instead of having to explicitly write:

foreach(object temp in collection)
{
     string item = (string)temp;

Granted, with .NET 2, this is not really an issue anymore.


The history of foreach predates generic IEnumerable and so it facilitated enumerating over collections such as ArrayList. Now that .NET has generic collections and ArrayList is rarely used, the free casting does seem like a bit of an impedance mismatch with the way it would have been designed if the feature were added now.

Nevertheless, now that we have the feature, you still see people use it even with generic collections to cast up to the type that they know they want, thereby avoiding a few lines of code. This is not too far removed from how it was used in the ArrayList days.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜