gette-6ren">
gpt4 book ai didi

c# - 创建一个 Action 到 "set"属性,当我为 "get"提供 LINQ 表达式时

转载 作者:可可西里 更新时间:2023-11-01 07:53:54 25 4
gpt4 key购买 nike

我希望能够生成编译表达式来设置属性,给定为属性提供“get”方法的 lambda 表达式。

这是我正在寻找的:

public Action<int> CreateSetter<T>(Expression<Func<T, int>> getter)
{
// returns a compiled action using the details of the getter expression tree, or null
// if the write property is not defined.
}

我仍在努力理解各种类型的 Expression 类,因此,如果您能为我指明正确的方向,那就太好了。

最佳答案

以@Ani 的回答为起点,您可以使用以下内容生成编译表达式

[TestMethod]
public void CreateSetterFromGetter()
{
Action<Person, int> ageSetter = InitializeSet((Person p) => p.Age);
Action<Person, string> nameSetter = InitializeSet((Person p) => p.Name);

Person p1 = new Person();
ageSetter(p1, 29);
nameSetter(p1, "John");

Assert.IsTrue(p1.Name == "John");
Assert.IsTrue(p1.Age == 29);
}

public class Person { public int Age { get; set; } public string Name { get; set; } }

public static Action<TContainer, TProperty> InitializeSet<TContainer, TProperty>(Expression<Func<TContainer, TProperty>> getter)
{
PropertyInfo propertyInfo = (getter.Body as MemberExpression).Member as PropertyInfo;

ParameterExpression instance = Expression.Parameter(typeof(TContainer), "instance");
ParameterExpression parameter = Expression.Parameter(typeof(TProperty), "param");

return Expression.Lambda<Action<TContainer, TProperty>>(
Expression.Call(instance, propertyInfo.GetSetMethod(), parameter),
new ParameterExpression[] { instance, parameter }).Compile();
}

您应该缓存编译后的表达式,以便多次使用。

关于c# - 创建一个 Action<T> 到 "set"属性,当我为 "get"提供 LINQ 表达式时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4596453/

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