Equivalent to expression. Add to .Net 3.5?

In .Net 4.0, Microsoft added Expression.Assign. I am stuck using 3.5. I am trying to come up with some ways to write a method that can set the property of an object, but so far I have been out of luck. I can do it:

public void Assign(object instance, PropertyInfo pi, object value)
{
    pi.SetValue(instance, value, null);
}

But I want to avoid the overhead of using reflection! Properties cannot be used with ref. Is it possible?

+3
source share
1 answer

Since you are trying to avoid reflection overhead, but are dealing with expression trees, I assume that you are trying to compile an expression for the delegate to set the property.

- . - .NET 3.5, Expression.Call. :

class Test{ public int X {get;set;} }

//...elsewhere
var xPropSetter = typeof(Test)
    .GetProperty("X",BindingFlags.Instance|BindingFlags.Public)
    .GetSetMethod();
var newValPar=Expression.Parameter(typeof(int));
var objectPar=Expression.Parameter(typeof(Test));
var callExpr=Expression.Call(objectPar, xPropSetter, newValPar);
var setterAction = (Action<Test,int>)
    Expression.Lambda(callExpr, objectPar, newValPar).Compile();
Test val = new Test();
Console.WriteLine(val.X);//0
setterLambda(val,42);
Console.WriteLine(val.X);//42

, , , , :

var setterAction = (Action<Test,int>)
    Delegate.CreateDelegate(typeof(Action<Test,int>), xPropSetter);
+8

Source: https://habr.com/ru/post/1782806/