将模板化方法作为对象传递给反射创建的method.invoke

时间:2014-12-18 15:39:01

标签: c# templates dynamic reflection delegates

我有一个按以下方式声明的函数:

public delegate void Callback<T>(T arg1) where T : EventT;
public void RegisterCallback<T>(Callback<T> callback) where T : EventT

我想通过反射来调用它,因为在运行时我不知道特定实例中的类型,我正在尝试

Type classType = Type.GetType (eventNameString);
MethodInfo baseMethod = eventDispatcher.GetType ().GetMethod ("RegisterCallback");
MethodInfo typedMethod = baseMethod.MakeGenericMethod(new Type[] {classType});

如果我理解正确的话现在正在制作一个除了这个动态类型的方法,但我关心的是如何将Callback参数传递给方法调用

typedMethod.Invoke (eventDispatcher, new object[] { ??? });

我不知道如何声明一个委托传递给对象[] params,它也将被输入agaisnt classType,我对Csharp也很新,所以有点迷失,

提前致谢

1 个答案:

答案 0 :(得分:0)

只需传递您委托的实例

即可
static void myglobalcallback(object arg)
{
    //....
}

var dmethod = new DynamicMethod(string.Empty, typeof(void), new Type[] { thegenerictype }, true);
var body = dmethod.GetILGenerator();
body.Emit(opcodes.ldarg_0);
body.Emit(opcodes.castclass, typeof(object));
body.emit(opcodes.call, typeof(mycurrenttype).getmethod("myglobalcallback"));
body.emit(opcodes.ret);
var delegate = dmethod.createdelegate(tyepof(Callbacl<>).MakegenericType(thegenericType));
new object[] { mydelegate }