How to dynamically call delegate chaining in VB.NET

Does anyone know if it is possible to dynamically create a call chain and call it?

Suppose I have two classes A and 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 the MethodInfo for Func () and Name () and call 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 that I can call from two MethodInfo objects, but that way I can only call the two functions separately and not as part of a call chain.

I would like to use two .NET 3.5 solutions using an expression tree and if possible a .NET 2.0 compatible solution

+1


source to share


2 answers


Are you using .NET 3.5? If so, it should be relatively easy to build an expression tree to represent it. I am missing a tree-fu expression to easily write a corresponding tree without VS open, but if you confirm it is an option, I get it working in notepad (from my Eee ... hence the lack of VS).

EDIT: Ok, 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 ...

+2


source


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

Expression ctorCall = Expression.Constructor(A)

      



And pass this expression as 1st parameter when creating fCall

Otherwise, we are missing the starting point for the chain, and we will get an exception when running the code.

0


source







All Articles