Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用动态类型调用泛型方法_C#_Generics - Fatal编程技术网

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

C# 使用动态类型调用泛型方法,c#,generics,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>

假设我有以下几节课

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
   }
}
公共类动物{….}
公营鸭:动物{…}
公共类奶牛:动物{…}
公共类创建者
{
公共列表CreateAnimals(整数)
{
类型=类型(T);
List returnList=新列表();
//使用反射填充列表并返回
}
}
现在,在后面的一些代码中,我想阅读要创建的动物

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);
Creator=新的创建者();
string animalType=//从文件中读取要创建的动物(鸭子、奶牛)
Type Type=Type.GetType(animalType);
列出动物=创建者。创建动物(5);

现在问题是最后一行无效。有什么优雅的方法可以做到这一点吗?

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


要使用反射,您需要使用
Type.GetMethod
来获取方法定义,然后调用,然后像调用任何其他方法一样调用它。

我不知道如何使用优雅,但方法是:

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

这方面的关键是MakeGenericType()和MakeGenericMethod()。一旦使用了动态类型,就不能真正回到静态类型。您可以使用
Activator.CreateInstance(typeof(list).MakeGenericType(type))
动态创建列表,然后使用类似的反射方法动态调用泛型方法。

尝试以下操作:

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
}
public List CreateAnimals(int numAnimals)其中T:Animal
{
类型=类型(T);
List returnList=新列表();
//使用反射填充列表并返回
}
它应该确保CreateAnimals允许的类型继承自Animal。然后,希望它不会出现
List animals=creator.CreateAnimals(5)的问题


您必须相应地修改约束类型。如果类型未知,则必须完全依赖反射…

如果OP希望读取从字符串创建的动物类型,则这并没有真正的帮助。尽管您无法将其转换为
List
List
等,除非您在编译时已经知道类型,而您不知道。最好是转换到
IList
List<animalType> animals = 
 creator.CreateAnimals<type>(5);
List<Animal> animals = 
  creator.CreateAnimals<Cow>(5);