I know this question has already been asked, but this time I have two additional constraints:
Reflection cannot be used.
I don't want to pass a wrapper around a property's setter. I want to pass the setter itself:
// NO! NO! NO!
myObject.MyMethod(value => anotherObject.AnotherProperty = value);
Define this helper function(You'll need to add the error checking):
Action<TObject,TValue> GetSetter<TObject,TValue>(Expression<Func<TObject,TValue>> property)
{
var memberExp=(MemberExpression)property.Body;
var propInfo=(PropertyInfo)memberExp.Member;
MethodInfo setter=propInfo.GetSetMethod();
Delegate del=Delegate.CreateDelegate(typeof(Action<TObject,TValue>),setter);
return (Action<TObject,TValue>)del;
}
And use it like this:
Action<MyClass,int> setter=GetSetter((MyClass o)=>o.IntProperty);
This is not exactly what you want(It uses reflection), but probably as close as you'll get. The returned delegate is the setter itself, no wrapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With