Create generic Func from reflection

Deadly 提交于 2021-02-06 12:46:56

问题


I've specified type in a variable: Type hiddenType. I need to create a Func<T> delegate where T is of type specified in mentioned variable and assign an method:

var funcType = typeof(Func<>).MakeGenericType(hiddenType);
Func<object> funcImplementation = () => GetInstance(hiddenType);

var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method);

It doesn't works - because funcImplementation is returns object instead of desired. At runtime, it will surely be an instance of type specified in hiddenType.

GetInstance returns object and signaure cannot be changed.


回答1:


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.




回答2:


Instead of using a Type, you could consider using a generic wrapper, if it's not possible for you to change the GetInstance signature:

private Func<THidden> GetTypedInstance<THidden>()
{
    return () => (THidden)GetInstance(typeof(THidden));
}

Then you can just call it with

GetTypedInstance<SomeClass>();

instead of

GetInstance(typeof(SomeClass));


来源:https://stackoverflow.com/questions/30916280/create-generic-func-from-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!