的foreach可以抛出一个InvalidCastException? [英] Foreach can throw an InvalidCastException?

查看:151
本文介绍了的foreach可以抛出一个InvalidCastException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下以下code:

Imagine the following code:

class foreach_convert
{
    public static void method2()
    {
        List<IComparable> x = new List<IComparable>();
        x.Add(5);

        foreach (string s in x)
        {
            //InvalidCastException in runtime
        }
    }
}

我不知道,这是为什么的foreach行为,所以......不是C#样?
这里发生的是隐式转换为一个子类,这是容易出错,似乎在语言中的每个其他地方被禁止。还是我不对?

I wonder, why is this foreach behavior so... not C#-like? What happens here is an implicit cast to a subclass, which is error-prone and seems to be banned in every other place in the language. Or am I not right?

P.S。我问的原因是,我在我的项目,我曾经从外部库,这是所谓的像 SomeTypeCollection ,但实际上提供的基本类型项目的集合,并可能载有 SomeOtherType 。我的错,但仍然没有语言,也没有提供任何明确提示/警告编译器,这是相当不寻常的C#...

P.S. The reason I'm asking is that I had a bug in the similar code in my project, where I used to iterate through a custom Collection from an external library, which was called like SomeTypeCollection, but in fact provided a collection of base type items and could have contained items of SomeOtherType. My fault, but still neither the language, nor the compiler provided any explicit hints/warnings, which is quite unusual for C#...

推荐答案

回想起以前的仿制药... 的foreach 不得不施展,让你可以做这样的事情懂事

Think back to before generics... foreach had to cast so that you could do sensible things like:

foreach (string x in names)
{
    // ...
}

而不是:

foreach (object tmp in names)
{
    string x = (string) tmp;
    // ...
}

后者只是恶心,海事组织。提供了隐式转换为不同语言的休息,但使得它更容易在绝大多数情况下使用。

The latter is just icky, IMO. Providing an implicit cast is unlike the rest of the language, but makes it much easier to use in the vast majority of cases.

我的犯罪嫌疑人的,如果C#有过泛型的的扩展方法入手(所以我们可以使用的 OfType 和的 铸造 )的的foreach 将不会完全一样的指定方式。

I suspect that if C# had had generics and extension methods to start with (so we could use OfType and Cast) that foreach wouldn't be specified in quite the same way.

请注意,在的foreach 更是奇怪:该类型没有实施的IEnumerable 可言。只要它有它返回的东西这反过来又的MoveNext()的GetEnumerator 方法>电流,C#编译器是幸福的。这意味着你可以仿制药之前,实施强类型的迭代器(避免拳击)。

Note that there's even more oddness in foreach: the type doesn't have to implement IEnumerable at all. So long as it has a GetEnumerator method which returns something which in turn has MoveNext() and Current, the C# compiler is happy. This meant you could implement a "strongly typed iterator" (to avoid boxing) before generics.

这篇关于的foreach可以抛出一个InvalidCastException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆