I\'m trying to improve my reflection code by creating Delegates for the Getter
and Setter
methods.
My code looks like this:
MyO
If your objective is to be able to invoke your action/function without knowing the return type at compile time, then you probably want to end up with an Action<object>
and Func<object>
, right?
You can do this without having to compile an expression tree or anything, like so:
// Use reflection to create the action, invoking the method below.
var setAction = (Action<object>) this.GetType()
.GetMethod("CastAction", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(prop.PropertyType)
.Invoke(null, new object[]{setMethod});
// invoke the action like this:
object value = 42; // or any value of the right type.
setAction(value);
Using this helper method:
private static Action<object> CastAction<T>(Delegate d)
{
var action = (Action<T>)d;
return obj => action((T)obj);
}
My tests show this to be roughly 25% faster than using dynamic
, and about 45% slower than just saying obj.Prop = 2
;
Is there a reason why you need to use Action<T> or Func<T> to dynamically get/set a propery?
If not you can use PropertyInfo.GetMethod() and SetMethod()
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Prop");
MethodInfo getter = prop.GetMethod();
getter.Invoke(...)
MethodInfo setter = prop.SetMethod();
setter.Invoke(...)