为什么跳过的foreach编译时类型检查的接口类型? [英] Why does foreach skip compile time type checking on interface types?

查看:141
本文介绍了为什么跳过的foreach编译时类型检查的接口类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用C#中的的foreach 循环,看来,如果项目类型是接口类型没有执行编译时类型检查。

When I use a foreach loop in C#, it appears that no compile time type checking is performed if the item type is an interface type.

例如:

class SomeClass {}
interface SomeInterface {}

IEnumerable<SomeClass> stuff;
foreach(SomeInterface obj in stuff) { // This compiles - why!?
}

这将愉快地编译和运行时导致异常,当它是在明确编译的时候这是没有意义的。如果我改变从 SomeInterface 项目类型到另一个类,然后编译时类型检查恢复:

This will happily compile and cause an exception at runtime, when it is clear at compile time this makes no sense. If I change the item type from SomeInterface to another class, then compile time type-checking is restored:

IEnumerable<SomeClass> stuff;
foreach(Random obj in stuff) { // This doesn't compile - good!
}



为什么没有编译时的类型检查时,该项目类型是接口?

Why is there no compile time type checks when the item type is an interface?

(这发生在Visual Studio .NET 3.5 SP1 2008)

(This occurs with .NET 3.5 SP1 in Visual Studio 2008)

推荐答案

这是不是在编译时明确有无程序的其他部分,也许在不同的项目中,有:

It is NOT clear at compile time whether another part of the program, maybe in a different project, has:

class SomeOtherClass : SomeClass, ISomeInterface
{
   public static IEnumerable<SomeClass> GetSomeStuff()
   {
      for( int i = 0; i<10; ++i)
         yield return new SomeOtherClass(i);
   }
}

现在运行时检查成功。

如果您标记 SomeClass的密封那么这是不可能的,这又可以知道在编译时,中投不会有任何效果。

If you mark SomeClass as sealed then this isn't possible, and it's again possible to know at compile time that the cast will never work.

这篇关于为什么跳过的foreach编译时类型检查的接口类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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