使用动态类型调用泛型方法

cmp*_*rer 50 c# generics

可以说我有以下课程

public class Animal { .... }

public class Duck : Animal { ... }

public class Cow : Animal { ... }

public class Creator
{
   public List<T> CreateAnimals<T>(int numAnimals)
   {
      Type type = typeof(T);
      List<T> returnList = new List<T>();
      //Use reflection to populate list and return
   }
}
Run Code Online (Sandbox Code Playgroud)

现在在一些代码中,我想读一下要创建的动物.

Creator creator = new Creator();
string animalType = //read from a file what animal (duck, cow) to create
Type type = Type.GetType(animalType);
List<animalType> animals = creator.CreateAnimals<type>(5);
Run Code Online (Sandbox Code Playgroud)

现在问题是最后一行无效.有没有一些优雅的方式来做到这一点?

Kir*_*oll 65

我不知道优雅,但做到这一点的方法是:

typeof(Creator)
    .GetMethod("CreateAnimals")
    .MakeGenericMethod(type)
    .Invoke(creator, new object[] { 5 });
Run Code Online (Sandbox Code Playgroud)

  • 虽然你不能把它转换为`List <Duck>`或`List <Cow>`等,除非你已经在编译时知道了这个类型,你不知道.你能做的最好就是施展为`IList`. (3认同)

Jon*_*eet 29

并不是的.基本上你需要使用反射.泛型实际上是针对静态类型而不是仅在执行时已知的类型.

要使用反射,您将使用Type.GetMethod获取方法定义,然后调用MethodInfo.MakeGenericMethod(type),然后像任何其他方法一样调用它.


Sam*_*uel 5

尝试这个:

public List<T> CreateAnimals<T>(int numAnimals) where T : Animal
{
    Type type = typeof(T);
    List<T> returnList = new List<T>();
    //Use reflection to populate list and return
}
Run Code Online (Sandbox Code Playgroud)

它应该确保 CreateAnimals 允许的类型继承自 Animal。那么希望不会有问题List<animalType> animals = creator.CreateAnimals<type>(5);

  • 如果OP想要从字符串中读取要创建的动物类型,那么这并没有真正的帮助。 (3认同)