Casting a Delegate into an Action or Func in runtime

前端 未结 2 2001
死守一世寂寞
死守一世寂寞 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 and Func, 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) 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 CastAction(Delegate d)
    {
        var action = (Action)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;

    提交回复
    热议问题