Equivalent of Expression.Assign in .Net 3.5?
In .Net 4.0 Microsoft added Expression.Assign. I'm stuck with using 3.5, though. I'm trying to come up with some means of write a method that can set the object property, but so far I haven't had much luck. I can do this:
public void Assign(object instance, PropertyInfo pi, object value)
{
pi.SetValue(instance, value, null);
}
But I want to avoid the overhead of using开发者_如何学Go reflection! Properties cannot be used with a ref
. Is this possible?
Since you're aiming to avoid the overhead of reflection but are dealing with expression trees, I'm assuming you're trying to compile an expression to a delegate to set a property.
All properties are simply get and set methods behind the scenes. These can be called - and this can be done in .NET 3.5 expression trees using Expression.Call
. For instance:
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
Note that if all you want is a delegate to set a value, you can also create the delegate without using an expression tree at all:
var setterAction = (Action<Test,int>)
Delegate.CreateDelegate(typeof(Action<Test,int>), xPropSetter);
精彩评论