构建表达式树并使用Expression.Call方法

时间:2011-12-09 03:14:07

标签: c# expression-trees

我有两个名为TClass1TClass2的虚拟类。我想知道如何构建一个表达式树来调用操作TClass1.TestMethod。我特别有问题使用Expression.Call方法基于类的实例方法创建表达式。任何帮助将不胜感激。

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 个答案:

答案 0 :(得分:10)

试试这段代码:

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();