我有一个类,它有一个泛型方法:
public class MyClass
{
public void MyMethod<T, IEntity>()
{
}
}在某些地方,我使用反射来执行它:
var intType = typeof(int);
var stringType = typeof(string);
MethodInfo method = typeof(MyClass).GetMethod(nameof(MyClass.MyMethod));
MethodInfo generic = method.MakeGenericMethod(intType, stringType);
generic.Invoke(myClass, null);它起作用了。在某些情况下,我需要在方法中使用Action:
myClass.MyMethod<Action<int>, string>();我如何使用反射来做到这一点呢?
发布于 2019-07-26 16:30:41
如果您知道编译时的第一个泛型参数为Action<int>,那么您可以只使用typeof(Action<int>)
var actionType = typeof(Action<int>);
var stringType = typeof(string);
MethodInfo method = typeof(MyClass).GetMethod(nameof(MyClass.MyMethod));
MethodInfo generic = method.MakeGenericMethod(actionType, stringType);
generic.Invoke(myClass, null);如果Action的泛型参数仅在运行时被称为Type的实例,则可以在运行时调用typeof(Action<>)上的MakeGenericType来构造操作类型:
var actionType = typeof(Action<>).MakeGenericType(someTypeObject);
var stringType = typeof(string);
MethodInfo method = typeof(MyClass).GetMethod(nameof(MyClass.MyMethod));
MethodInfo generic = method.MakeGenericMethod(actionType, stringType);
generic.Invoke(myClass, null);https://stackoverflow.com/questions/57215910
复制相似问题