Create delegate with types known at runtime

前端 未结 2 1198
清歌不尽
清歌不尽 2021-01-24 03:00

How can I create a Delegate with types only known at run time ?

I would like to do the following :

Type type1 = someObject.getType();
Type type2 = someOt         


        
相关标签:
2条回答
  • 2021-01-24 03:12

    I suspect you want Expression.GetFuncType as a simpler way of doing your typeof(...).MakeGenericType operation.

    var delegateType = Expression.GetFuncType(type1, type2);
    Delegate getter = Delegate.CreateDelegate(delegateType, someMethodInfo);
    

    You can't have a compile-time type for getter that's more specific than Delegate though1, because you simply don't know that type at compile-time. You could potentially use dynamic though, which would make it easier to invoke the delegate:

    dynamic getter = ...;
    var result = getter(input);
    

    1 As noted in comments, you could cast to MulticastDelegate, but it wouldn't actually buy you anything.

    0 讨论(0)
  • 2021-01-24 03:36

    You could create a generic method for that:

    public Func<T1, T2> GetFunc<T1, T2>(T1 Object1, T2 Object2, MethodInfo Method)
    {
        return (Func<T1, T2>)Delegate.CreateDelegate(typeof(Func<,>).MakeGenericType(typeof(T1), typeof(T2)), Method);
    }
    

    And I bet you can do something using the same philosophy with the Method to avoid all this reflection stuff.

    Obs: that would work only if T1 and T2 are typed variables. If they are as object you'll get a Func<object, object>. But....if the objects you will give to the method are as object as well, that would be no problem at all. And maybe you can even use Func<object, object> always, depending on your scenario.

    0 讨论(0)
提交回复
热议问题