Create generic Func from reflection

后端 未结 2 1562
陌清茗
陌清茗 2021-02-10 00:52

I\'ve specified type in a variable: Type hiddenType. I need to create a Func delegate where T is of type specified in mentioned v

2条回答
  •  后悔当初
    2021-02-10 01:04

    You can solve this by building an expression tree manually, and inserting a cast to hiddenType. This is allowed when you construct an expression tree.

    var typeConst = Expression.Constant(hiddenType);
    MethodInfo getInst = ... // <<== Use reflection here to get GetInstance info
    var callGetInst = Expression.Call(getInst, typeConst);
    var cast = Expression.Convert(callGetInst, hiddenType);
    var del = Expression.Lambda(cast).Compile();
    

    Note: the above code assumes that GetInstance is static. If it is not static, change the way you construct callGetInst to pass the object on which the method is invoked.

提交回复
热议问题