views:

74

answers:

2

Ultimately, I'm looking forward to a reflection based approach to create a delegate wrapper for a method B(C(),D()) - to some what like (c,d)=>B(()=>c(),()=>d())

First question - Given that you've a Methodinfo, what are the considerations to create a delegate type (via reflection) which corresponds to that method signature?

Do you have a reference to the code chunk of any open source projects that does this? :P

Update: Here is a generic way to create a delegate for a methodinfo http://stackoverflow.com/questions/1124563/builds-a-delegate-from-methodinfo - I think recursively wrapping the parameters part is something I've to work out over the weekend.

A: 

Use Expression to build dynamic methods. Here is an example according to your question. I'm taking Console.Write(string s) as an example.

    MethodInfo method = typeof(Console).GetMethod("Write", new Type[] { typeof(string) });
    ParameterExpression parameter = Expression.Parameter(typeof(string),"str");
    MethodCallExpression methodExp = Expression.Call(method,parameter);
    LambdaExpression callExp = Expression.Lambda(methodExp, parameter);
    callExp.Compile().DynamicInvoke("hello world");
Danny Chen
Nope. A better, generic approach is here http://stackoverflow.com/questions/1124563/builds-a-delegate-from-methodinfo - but that don't wrap the parameters.
amazedsaint
A: 

I managed to create a working delegate from the MethodInfo of a method like this:

Method and delegate:

public static int B(Func<int> c, Func<int> d) {
  return c() + d();
}

public delegate int TwoFunc(Func<int> c, Func<int> d);

Code:

MethodInfo m = typeof(Program).GetMethod("B");
TwoFunc d = Delegate.CreateDelegate(typeof(TwoFunc), m) as TwoFunc;
int x = d(() => 1, () => 2);
Console.WriteLine(x);

Output:

3

Not sure how useful it is, though...

Guffa
+1 for the last line
Matt Ellen