I need to write a function that receives a property as a parameter and execute its getter.
If I needed to pass a function/delegate I would have used:
delegate RET FunctionDelegate<T, RET>(T t);
void func<T, RET>(FunctionDelegate function, T param, ...)
{
...
return function.Invoke(param);
}
Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?
You can also write something like:
static void Method<T, U>(this T obj, Expression<Func<T, U>> property)
{
var memberExpression = property.Body as MemberExpression;
//getter
U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);
//setter
obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);
}
and example of invocation:
DbComputerSet cs = new DbComputerSet();
cs.Method<DbComputerSet, string>(set => set.Code);
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