为什么 foreach 跳过接口类型的编译时类型检查?
当我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在编译时尚不清楚程序的另一部分(可能在不同的项目中)是否具有:
现在运行时检查成功。
如果您将
SomeClass
标记为sealed
那么这是不可能的,并且在编译时又可能知道该转换永远不会起作用。It is NOT clear at compile time whether another part of the program, maybe in a different project, has:
Now the runtime check SUCCEEDS.
If you mark
SomeClass
assealed
then this isn't possible, and it's again possible to know at compile time that the cast will never work.