将新对象分配给类属性C#表达式树

时间:2018-03-05 05:31:01

标签: c# lambda linq-expressions

如何使用表达式树

分配以下语句
  

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;

1 个答案:

答案 0 :(得分:0)

由于目标表达式为:

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