问题
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