List 实现了 IList 接口,所以我期望 IList 将接受 List 对象,
但是为什么 IList<T> 不接受 List<T> 呢?
static IList<int> List_1()
{
List<int> list = new List<int> { 1,2,3,3,4,5};
return list;
}
static IList<IList<int>> List_2()
{
List<List<int>> parent = new List<List<int>>();
List<int> list = new List<int> { 1, 2, 3, 3, 4, 5 };
parent.Add(list);
return parent; //compiler error CS0266
}
List<object>
不接受List<string>
吗? - SweeperMyClass
派生自object
,就像List<T>
派生自IList<T>
一样。所以如果你有一个返回List<object>
的方法,你不能返回List<MyClass>
,除非进行强制转换。 - SᴇM