Why does foreach skip compile time type checking on interface types?

末鹿安然 提交于 2019-12-04 05:22:25

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);
   }
}

Now the runtime check SUCCEEDS.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!