使用动态类型调用泛型方法 [英] Calling a generic method with a dynamic type
本文介绍了使用动态类型调用泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下课程
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
}
}
现在在稍后的一些代码中我想阅读要创建的动物.
Now in some code later I want to read in what animal to create.
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);
现在的问题是最后一行无效.那么有没有什么优雅的方法可以做到这一点?
Now the problem is the last line isn't valid. Is there some elegant way to do this then?
推荐答案
我不知道优雅,但这样做的方法是:
I don't know about elegant, but the way to do it is:
typeof(Creator)
.GetMethod("CreateAnimals")
.MakeGenericMethod(type)
.Invoke(creator, new object[] { 5 });
这篇关于使用动态类型调用泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文