将新对象分配给类属性C#表达式树
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将新对象分配给类属性C#表达式树相关的知识,希望对你有一定的参考价值。
如何使用表达式Tree分配以下语句
myFoo.myBar = new Bar();
我的守则如下 -
public static Action<TObject, TProperty>CreateNewObjectAndSet<TObject,TProperty>(string propertyName)
{
ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));
MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyName);
var newObject = Expression.New(typeof(TProperty));
var x = Expression.Assign(propertyGetterExpression, newObject);
var paramExpressions = new ParameterExpression[2];
paramExpressions[0] = paramExpression;
paramExpressions[1] = newObject;
Action<TObject, TProperty> result = Expression.Lambda<Action<TObject, TProperty>>(x, paramExpressions).Compile();
return result;
}
语句处发生编译错误
paramExpression [1] = newObject;
答案
由于目标表达式是:
myFoo.myBar = new Bar();
你不需要2个参数,你只需要1 - myFoo
实例来设置属性。所以改变你的代码是这样的:
public static Action<TObject> CreateNewObjectAndSet<TObject, TProperty>(string propertyName) where TProperty: new() {
ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));
MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyName);
var newObject = Expression.New(typeof(TProperty));
var x = Expression.Assign(propertyGetterExpression, newObject);
var paramExpressions = new ParameterExpression[1];
paramExpressions[0] = paramExpression;
Action<TObject> result = Expression.Lambda<Action<TObject>>(x, paramExpressions).Compile();
return result;
}
然后像这样打电话:
var setter = CreateNewObjectAndSet<Foo, Bar>("myBar");
setter(myFoo);
以上是关于将新对象分配给类属性C#表达式树的主要内容,如果未能解决你的问题,请参考以下文章
将指针分配给指针(并将指针传递给类)时使用删除的 C++ 混淆