调用带有动态类型的通用方法 [英] Calling a generic method with a dynamic type

查看:110
本文介绍了调用带有动态类型的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有以下类

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
   }
}

现在在一些code后,我想创造什么动物来读取。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆