Casting a Delegate into an Action or Func in runtime

前端 未结 2 2006
死守一世寂寞
死守一世寂寞 2021-02-14 21:33

I\'m trying to improve my reflection code by creating Delegates for the Getter and Setter methods.

My code looks like this:

MyO         


        
相关标签:
2条回答
  • 2021-02-14 22:08

    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;

    0 讨论(0)
  • 2021-02-14 22:10

    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(...)
    
    0 讨论(0)
提交回复
热议问题