Expression to create an instance with object initializer

后端 未结 2 1413
闹比i
闹比i 2020-12-25 15:09

Is there any way to create an instance of an object with object initializer with an Expression Tree? I mean create an Expression Tree to build this lambda:

/         


        
2条回答
  •  悲哀的现实
    2020-12-25 15:22

    To represent object initializers in an Expression, you should use Expression.MemberInit():

    Expression> BuildLambda() { 
        var createdType = typeof(MyObject);
        var displayValueParam = Expression.Parameter(typeof(bool), "displayValue"); 
        var ctor = Expression.New(createdType);
        var displayValueProperty = createdType.GetProperty("DisplayValue");
        var displayValueAssignment = Expression.Bind(
            displayValueProperty, displayValueParam);
        var memberInit = Expression.MemberInit(ctor, displayValueAssignment);
    
        return
            Expression.Lambda>(memberInit, displayValueParam);
    }
    

    To verify this actually does what you want, you can call ToString() on the created expression. In this case, the output is as expected:

    displayValue => new MyObject() {DisplayValue = displayValue}
    

提交回复
热议问题