简而言之,我希望能够通过在所使用的所有类型中使用父类型,在数组中使用不同类型参数来存储泛型.MSDN提到这是不可能的,因为泛型是不变的类型,但是一条评论声明自4.0框架以来这种情况发生了变化.
这是我想要做的基本示例:
public class Animal
{
}
public class Dog : Animal
{
}
public class Cat : Animal
{
}
public class MyGeneric<T>
{ }
public class MyInheritedGeneric<T> : MyGeneric<T>
{ }
static void Main(string[] args)
{
MyGeneric<Animal>[] myGenericArray = new MyGeneric<Animal>[]
{
new MyGeneric<Dog>(),
new MyInheritedGeneric<Cat>()
};
}
Run Code Online (Sandbox Code Playgroud)
这会返回类似的错误:
Cannot implicitly convert type
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Dog>' to
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Cannot implicitly convert type
'InheritanceTest.Program.MyInheritedGeneric<InheritanceTest.Program.Cat>'
to 'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Run Code Online (Sandbox Code Playgroud)
有没有办法使用类型的父类将泛型存储在数组中,或者这根本不可能?我真的希望有可能,否则会让我的节目成为一场噩梦......
编辑:更多背景!
我正在制作课程以在游戏中产生敌人.我称之为模板(与实际的模板类无关,我很可能称之为蓝图或工厂).敌人构造函数接受一个模板,它用它来确定自己的值.当游戏加载时,模板用于生成所有敌人,使用他们的Generate()函数,该函数返回他们被分配生成的相应类型的数组.使用模板创建的所有对象都有一个构造函数,它将模板作为唯一参数.
public class Template<T>
{
protected static Random random = new Random();
protected …Run Code Online (Sandbox Code Playgroud)