为什么 foreach 跳过接口类型的编译时类型检查?

发布于 2024-09-12 03:47:48 字数 567 浏览 0 评论 0原文

当我在 C# 中使用 foreach 循环时,如果项类型是接口类型,则似乎不会执行编译时类型检查。

例如,

class SomeClass {}
interface SomeInterface {}

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

这将愉快地编译并在运行时引发异常,而在编译时很清楚这是没有意义的。如果我将项目类型从 SomeInterface 更改为另一个类,则编译时类型检查将恢复:

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

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

(Visual Studio 2008 中的 .NET 3.5 SP1 会出现这种情况)

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.

E.g.

class SomeClass {}
interface SomeInterface {}

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

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

穿越时光隧道 2024-09-19 03:47:49

在编译时尚不清楚程序的另一部分(可能在不同的项目中)是否具有:

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

现在运行时检查成功。

如果您将 SomeClass 标记为 sealed 那么这是不可能的,并且在编译时又可能知道该转换永远不会起作用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文