Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Objects of a specific type in foreach from an IEnumerable

I'm working with a legacy collection object that only implements non-generic IEnumerable and ICollection. What exactly happens with this object when I try to use this object with a foreach giving a more specific type on the LHS of the foreach expression?

// LegacyFooCollection implements non-generic IEnumerable
LegacyFooCollection collection = GetFooCollection();
foreach (Foo f in collection)
{
    // etc.
}

I know (because I've tried it) that this is safe when everything in collection really is of type Foo, but what happens if that fails?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The C# compiler performs the cast implicitly for you. In terms of the casting (but only in those terms1) it's equivalent to:

foreach (object tmp in collection)
{
    Foo f = (Foo) tmp;
    ...
}

Note that this will happen with generic collections too:

List<object> list = new List<object> { "hello", "there", 12345 };

// This will go bang on the last element
foreach (string x in list) 
{
}

This is all detailed in section 8.8.4 of the C# 4 spec.

If you're using .NET 3.5 or higher and you want to only select items of the appropriate type, you can use Enumerable.OfType:

LegacyFooCollection collection = GetFooCollection();
foreach (Foo f in collection.OfType<Foo>())
{
    // etc.
}

That may not be necessary for a LegacyFooCollection, but it can be useful when you're trying to find (say) all the TextBox controls in a form.


1 The differences are:

  • In your original code, f is read-only; in the "conversion" it's writable
  • In your original code, if you capture f you will (currently) capture a single variable across all iterations, as opposed to a separate variable per iteration in the "conversion"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...