Passing a Type to a generic method at runtime [duplicate]

你。 提交于 2020-01-30 04:08:24

问题


I have something like this

Type MyType = Type.GetType(FromSomewhereElse);

var listS = context.GetList<MyType>().ToList();

I would like to get the Type which is MyType in this case and pass it to the Generic Type method GetList

This is the error I am getting:

The type or namespace name 'MyType' could not be found (are you missing a using directive or an assembly reference?)


回答1:


You can use reflection and construct your call like this:

Type MyType = Type.GetType(FromSomewhereElse);

var typeOfContext = context.GetType();

var method = typeOfContext.GetMethod("GetList");

var genericMethod = method.MakeGenericMethod(MyType);

genericMethod.Invoke(context, null);

Note that calling methods with reflection will add a huge performance penalty, try to redesign your solution if possible.




回答2:


You'll have to use reflection:

var method = context.GetType()
    .GetMethod("GetList").MakeGenericMethod(MyType)

IEnumerable result = (IEnumerable)method.Invoke(context, new object[0]);
List<object> listS = result.Cast<object>().ToList();

However there's no way to use your type instance MyType as a static type variable, so the best you can do is to type the results as object.




回答3:


You don't build generics dynamically using type. Generics are filled in with a the name of the class, not a type.

You could use Activator.CreateInstance to create a generic type. You'll have to build the generic type dynamically.

To create a generic type dynamically.

Type listFactoryType = typeof(GenericListFactory<>).MakeGenericType(elementType);
var dynamicGeneric = (IListFactory)Activator.CreateInstance(listFactoryType);

Instead of getting the List using a generic method, you could create a generic class that exposes that method. You could derive from an interface like so.

interface IListFactory
{
   IList GetList();
}

class GenericListFactory<T>
{
   public IList GetList() { return new List<T>(); }
}


来源:https://stackoverflow.com/questions/16699340/passing-a-type-to-a-generic-method-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!