views:

756

answers:

2

Does someone knows if it's possible to dynamically create a call chain and invoke it?

Lets say I have two classes A & B:

public class A
    public function Func() as B
        return new B()
    end function
end class

public class B
   public function Name() as string
      return "a string";
   end function
end class

I want to be able to get MethodInfo for both Func() & Name() and invoke them dynamically so that I can get a call similar to A.Func().Name().

I know I can use Delegate.CreateDelegate to create a delegate I can invoke from the two MethodInfo objects but this way I can only call the two functions separately and not as part of a call chain.

I would like two solutions one for .NET 3.5 using expression tree and if possible a solution that is .NET 2.0 compatible as well

+1  A: 

Are you using .NET 3.5? If so, it should be relatively straightforward to build an expression tree to represent this. I don't have enough expression-tree-fu to easily write the relevant tree without VS open, but if you confirm that it's an option, I'll get to work in notepad (from my Eee... hence the lack of VS).

EDIT: Okay, as an expression tree, you want something like (C# code, but I'm sure you can translate):

// I assume you've already got fMethodInfo and nameMethodInfo.
Expression fCall = Expression.Call(null, fMethodInfo);
Expression nameCall = Expression.Call(fCall, nameMethodInfo);
Expression<Func<string>> lambda = Expression.Lambda<Func<string>>(nameCall, null);
Func<string> compiled = lambda.Compile();

This is untested, but I think it should work...

Jon Skeet
Yes you can use 3.5 to solve this problem - although I would prefer a 2.0 compatible solution (if one exists)
Dror Helper
Apparently you can code quite well using Notepad
Dror Helper
A: 

You need t add this line before the 1st expression:

Expression ctorCall = Expression.Constructor(A)

And pass that expression as the 1st parameter when creating fCall

Otherwise we're missing a starting point for the chain and we'll get an exception when running the code

Dror Helper