1

在 C# 中,我尝试使用 linq 表达式来生成对某些方法的调用。该方法的参数之一是委托。我有我想作为委托传递的方法的 MethodInfo 我只是不确定用于创建委托的 linq 语法。

这有点做作,但我希望这表明我正在尝试做的事情:

[C#]
delegate void Example();

object instance = ...;
MethodInfo methodToCall = ...;
MethodInfo methodToReference = instance.GetType().GetMethod("Foo");
var lambda = Expression.Call(
    methodToCall,
    Expression.New(
      typeof(Example).GetConstructor(new [] { typeof(object), IntPtr }),
      Expression.Constant(instance),
      Expression.Constant(/* IntPtr from MethodInfo?? */)));

lambda.Compile()();

问题是委托的构造函数要求一个 IntPtr,我不知道如何得到它!有没有比尝试使用 New() 表达式方法更直接的方法来创建委托对象?

4

1 回答 1

1
Example e = (Example)Delegate.CreateDelegate(typeof(Example), instance, methodToReference);
于 2011-01-08T17:53:18.550 回答