gpt4 book ai didi

c# - 鉴于此 lambda,我如何使用表达式树手动编写它?

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:34 25 4
gpt4 key购买 nike

class Program
{
static void Main(string[] args)
{
Expression<Func<string[], Poco>> exp = a => new Poco { MyProperty1 = a[0], MyProperty2 = a[1], MyProperty3 = a[2] };
var lambda = exp.Compile();

var output = lambda(new[] {"one", "two", "three"});

Console.WriteLine(output.MyProperty1);
}
}

class Poco
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
public string MyProperty3 { get; set; }
}

我对调用 lambda 的部分不感兴趣,那只是为了完整性。我在尝试浏览表达式树时完全迷路了,这可能会教我如何钓鱼。

最佳答案

private static Expression<Func<string[], Poco>> CreateExpr()
{
ParameterExpression paramExpr = Expression.Parameter(typeof(string[]), "a");
var newExpr = Expression.New(typeof(Poco));

var memberExprs = Enumerable.Range(0, 3)
.Select(i =>
{
string propertyName = "MyProperty" + (i + 1);
var property = typeof(Poco).GetProperty(propertyName);
Expression.Bind(property, Expression.ArrayIndex(paramExpr, Expression.Constant(i)));
});

var expr = Expression.MemberInit(newExpr, memberExprs);
return Expression.Lambda<Func<string[], Poco>>(expr, paramExpr);
}

关于c# - 鉴于此 lambda,我如何使用表达式树手动编写它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13310674/

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