我在变量中指定了类型:Type hiddenType
。我需要创建一个Func<T>
委托,其中T
是在上述变量中指定的类型,并指定一个方法:
var funcType = typeof(Func<>).MakeGenericType(hiddenType);
Func<object> funcImplementation = () => GetInstance(hiddenType);
var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method);
它不起作用 - 因为funcImplementation
返回object
而非所需。在运行时,它肯定是hiddenType
中指定的类型的实例。
GetInstance
返回object
,并且无法更改签名。
答案 0 :(得分:2)
您可以通过手动构建表达式树并将强制转换插入hiddenType
来解决此问题。构造表达式树时允许这样做。
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
的方式以传递调用该方法的对象。
答案 1 :(得分:0)
如果您无法更改GetInstance签名,则可以考虑使用通用包装,而不是使用Type:
private Func<THidden> GetTypedInstance<THidden>()
{
return () => (THidden)GetInstance(typeof(THidden));
}
然后你可以用
来调用它GetTypedInstance<SomeClass>();
而不是
GetInstance(typeof(SomeClass));