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?)
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
cmd/compile: generic functions are significantly slower than identical non-generic functions in some cases #50182.
A generic method can also be overloaded by nongeneric methods. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call—an error occurs if two or more overloaded methods both could be considered best ...
Multiple interface constraints can be specified. The constraining interface can also be generic.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With