gpt4 book ai didi

c# - 如何通过表达式赋值?

转载 作者:太空狗 更新时间:2023-10-29 18:20:24 25 4
gpt4 key购买 nike

如果我能够通过 Lambda 表达式进行赋值(如下),这将非常简单

//An expression tree cannot contain an assignment operator
Expression<Func<ComplexObj, object>> expression = obj => obj.Contacts[0].FirstName = "Tim";

由于赋值运算符,上述代码无效。我需要传递一个 lambda 表达式来识别复杂对象中需要设置的属性。在某些情况下,复杂对象具有 List,因此有重复的对象类型和名称,这就是为什么我需要 lambda 显式引用要更新的对象中的字段。

我可以使用以下方法检索值,没问题。但我不确定如何使用相同的逻辑来设置值,我遇到了 Expression.Assign 并相信这可能是解决方案。

Expression<Func<ComplexObj, object>> expression = obj => obj.Contacts[0].FirstName;
var result = FindByProperty(expression);

public static string FindByProperty(Expression<Func<Contract, object>> propertyRefExpr)
{
ComplexObj obj = new ComplexObj();
Contact myContact = new Contact();
myContact.FirstName = "Allen";
obj.Contacts = new List<Contact>{myContact};
return propertyRefExpr.Compile().Invoke(obj);
}

更新:

“将属性赋值作为表达式树传递给方法...”

将 SetValue 方法与 ParentTypeA 一起使用,Value 将不起作用。 (代码下方)

Expression<Func<ComplexObj, object>> expression = obj => obj.Contacts[0].FirstName;
obj.AssignNewValue(expression, firstName);

public static void AssignNewValue(this ComplexObj obj, Expression<Func<ComplexObj, object>> expression, object value)
{
var propertyInfo = (PropertyInfo)((MemberExpression)expression.Body).Member;
propertyInfo.SetValue(obj, value, null);
}

最佳答案

我最终使用了以下解决方案。干杯

ComplexObj obj = new ComplexObj();
Expression<Func<ComplexObj, object>> expression = obj => obj.Contacts[index].FirstName;
obj.AssignNewValue(expression, firstName);

public static void AssignNewValue(this ComplexObj obj, Expression<Func<ComplexObj, object>> expression, object value)
{
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object));
Expression targetExpression = expression.Body is UnaryExpression ? ((UnaryExpression)expression.Body).Operand : expression.Body;

var newValue = Expression.Parameter(expression.Body.Type);
var assign = Expression.Lambda<Action<ComplexObj, object>>
(
Expression.Assign(targetExpression, Expression.Convert(valueParameterExpression, targetExpression.Type)),
expression.Parameters.Single(),
valueParameterExpression
);

assign.Compile().Invoke(obj, value);
}

关于c# - 如何通过表达式赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13769780/

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