gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:19:42 26 4
gpt4 key购买 nike

我有两个虚拟类,分别名为 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; }
}

最佳答案

试试这段代码:

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

关于c# - 构建表达式树并使用 Expression.Call 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8440609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com