开发者

How does foreach cast without explicit/implicit overrides?

So I'm just learning C#, and came across something that I find odd... I'm playing with delegates and have creates a delegate DelegateReturnsInt. Now, When I use a foreach loop, the book shows to use it like this:

foreach(DelegateReturnsInt del in theDelegate.getInvocationList())

now I know that getInvocationList() returns an Array of Delegate[], but how does it convert them to DelegateReturnsInt? I ask because I wanted to just play around and change it from a foreach to a for loop, so I created this

Delegate[] del = theDelegate.GetInvocationList();
for(int开发者_C百科 i = 0; i < del.Length; i++){
    int result = del[i]();

but that doesn't see del[i] as a method. I've tried casting to DelegateReturnsInt and such, but it gives me cast type errors about not having it defined.

My big question is what makes foreach() so special?


It does an implicit cast (if you look at the emitted IL, you'd see it). This also means you could get an unexpected cast exception on that line if it's not what you say it is.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜