Reputation: 13665
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?
Upvotes: 1
Views: 1816
Reputation: 144136
Example e = (Example)Delegate.CreateDelegate(typeof(Example), instance, methodToReference);
Upvotes: 1