通过反射创建通用功能 [英] Create generic Func from reflection
问题描述
我在变量中指定了类型: Type hiddenType
.我需要创建一个 Func< T>
委托,其中 T
是上述变量中指定的类型,并分配一个方法:
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);
它不起作用-因为 funcImplementation
返回的是 object
,而不是所需的.在运行时,它肯定是 hiddenType
中指定的类型的实例.
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
返回 object
,并且不能更改签名.
GetInstance
returns object
and signaure cannot be changed.
推荐答案
您可以通过手动构建表达式树并将类型转换插入 hiddenType
来解决此问题.构造表达式树时,这是允许的.
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();
注意:以上代码假定 GetInstance
是 static
.如果不是静态的,则更改构造 callGetInst
的方式以传递在其上调用方法的对象.
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.
这篇关于通过反射创建通用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!