Using Expression and creating Expression Trees Method to invoke

c# expression-trees

Question

Two fake classes with namesTClass1 and TClass2 . To call the procedure, I need to know how to create an expression tree.TClass1.TestMethod I particularly struggle with utilizingExpression.Call technique to build an expression using a class's instance methods. We would appreciate any assistance.

public class TClass1
{
    public string Prop1 { get; set; }
    public int Prop2 { get; set; }

    public TClass2 TestMethod(TClass2 tc2, int c)
    {
        return new TClass2() { Cprop1 = "The result: " + this.Prop1 + ".", Cprop2 = this.Prop2 * c };
    }
}

public class TClass2
{

    public string Cprop1 { get; set; }
    public int Cprop2 { get; set; }
}
1
2
12/19/2011 11:06:43 AM

Accepted Answer

Attempt this code:

var par1 = Expression.Parameter(typeof(TClass2), "tc2");
var par2 = Expression.Parameter(typeof(int), "c");
var instance = Expression.Parameter(typeof(TClass1), "inst");
var inExp = Expression.Call(instance,typeof(TClass1).GetMethod("TestMethod"),par1,par2);
var exp = Expression.Lambda<Func<TClass1,TClass2,int,TClass2>>(inExp,instance,
                                                                   par1,par2);
var deleg = exp.Compile();
10
12/19/2011 11:02:39 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow