相关疑难解决方法(0)

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

可以说我有以下课程

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)

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

c# generics

50
推荐指数
3
解决办法
6万
查看次数

标签 统计

c# ×1

generics ×1