使用 linq 表达式如何创建并返回委托?
在 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() 表达式方法更直接的方法来创建委托对象?
In C# I am attempting to use linq expressions to generate calls to certain methods. One of the parameters to the method is a delegate. I have the MethodInfo for the method I want to pass as a delegate I just am not sure of the linq syntax for creating delegates.
This is a bit contrived but I hope this shows what I'm trying to do:
[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()();
The problem is that the constructor for a delegate is asking for an IntPtr, I am not sure how to get that! Is there a more direct way to create a delegate object than trying to use the New() expression method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)