Sna*_*ake 4 .net c# generics list
我想这样做:
List<Parent> test = new List<Child>();
Run Code Online (Sandbox Code Playgroud)
我班的完整代码是这样的:
class Program
{
public static void Main(string[] args)
{
List<Parent> test = new List<Child>();
test.Add(new Child());
test.Add(new AnotherChild());
}
}
class Parent { }
class Child : Parent { }
class AnotherChild : Parent { }
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么这给了我这个错误:
错误2无法将类型'System.Collections.Generic.List'转换为'System.Collections.Generic.List'd:\ personal\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 20 24 ConsoleApplication3
为什么这有效?
Parent[] test = new Child[10];
List<Parent> result = test.ToList();
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
- 对:
现在我知道原因了:List被编译为List`1和List to List`2.他们没有任何关系.