下面的代碼無法編譯(使用VS2010),我不明白爲什麼。編譯器應該能夠推斷List<TestClass>
與IEnumerable<ITest>
是「兼容的」(對不起,因爲缺少一個更好的詞),但不知何故它沒有。我在這裏錯過了什麼?C#編譯器無法識別一個類正在實現一個接口
interface ITest {
void Test();
}
class TestClass : ITest {
public void Test() {
}
}
class Program {
static void Test(IEnumerable<ITest> tests) {
foreach(var t in tests) {
Console.WriteLine(t);
}
}
static void Main(string[] args) {
var lst = new List<TestClass>();
Test(lst); // fails, why?
Test(lst.Select(t=>t as ITest)); //success
Test(lst.ToArray()); // success
}
}
編譯器給出兩個錯誤:
關於「ConsoleApplication1.Program.Test(System.Collections.Generic.IEnumerable < ConsoleApplication2最好重載方法匹配.ITest >)'有一些無效論據
參數1:無法從 'System.Collections.Generic.List <ConsoleApplication2.TestClass>' 轉換爲 'System.Collections.Generic.IEnumerable <ConsoleApplication2.ITest>'