我試圖理解爲什麼這個轉換不起作用:爲什麼這個C#代碼示例沒有工作?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastTest {
class Foo {}
// I want to use this kind of like a typedef, to avoid writing List<Foo> everywhere.
class FooList : List<Foo> {}
class Program {
static void Main(string[] args) {
FooList list = (FooList) Program.GetFooList();
}
// Suppose this is some library method, and i don't have control over the return type
static List<Foo> GetFooList() {
return new List<Foo>();
}
}
}
這會產生一個運行時錯誤:
InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[CastTest.Foo]' to type 'CastTest.FooList'.
任何人都可以解釋爲什麼這不工作,以及是否我可以以某種方式解決這個問題?
哪一行產生錯誤? – ChrisF 2012-03-05 22:26:52
這是正確的說:FooList是列表,或列表是FooList? –
2012-03-05 22:29:43
@AnthonyPegram前者。 – hvd 2012-03-05 22:31:33