【发布时间】:2013-12-10 21:05:25
【问题描述】:
我知道这段代码不起作用(并且以一种可行的方式编写它没有问题)。 我想知道编译器如何构建没有任何错误。如果你在哪里运行它,你会得到运行时错误? (假设数据不为空)
using System;
using System.Collections.Generic;
public class Class1
{
public void Main()
{
IEnumerable<IEnumerable<Foo>> data = null;
foreach(Foo foo in data){
foo.Bar();
}
}
}
public class Foo {
public void Bar() { }
}
【问题讨论】:
-
Resharper 用
Suspicious cast警告捕获它。仍然可以编译。 -
@user2864740 这有点像
.Cast<Foo>,但仍然只是像那样,不完全是发生了什么。 -
我猜这是因为 IEnumerable 是一个接受任何类的泛型类。由于 IEnumerable 是一个类,所以编译器没有错。
-
@user2864740 IT 会在运行时抛出
System.InvalidCastException。
标签: c# .net foreach ienumerable