C# 从反射创建泛型Func

C# 从反射创建泛型Func,c#,reflection,delegates,C#,Reflection,Delegates,我在变量中指定了类型:type hiddenType。我需要创建一个Func委托,其中T属于上述变量中指定的类型,并分配一个方法: var funcType = typeof(Func<>).MakeGenericType(hiddenType); Func<object> funcImplementation = () => GetInstance(hiddenType); var myFunc= Delegate.CreateDelegate(funcType

我在变量中指定了类型:
type hiddenType
。我需要创建一个
Func
委托,其中
T
属于上述变量中指定的类型,并分配一个方法:

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

var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method);
var funcType=typeof(Func).MakeGenericType(hiddenType);
Func funcImplementation=()=>GetInstance(hiddenType);
var myFunc=Delegate.CreateDelegate(funcType,valueGenerator.Method);
它不起作用-因为
funcImplementation
返回的是
object
,而不是所需的。在运行时,它肯定是
hiddenType
中指定类型的实例


GetInstance
返回
对象
,并且无法更改signaure。

您可以通过手动构建表达式树,并向
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();
var-typeConst=Expression.Constant(hiddenType);

MethodInfo getInst=…//

不要使用类型,如果不能更改GET实例签名,可以考虑使用通用包装器:

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

我看不出你想要实现什么。由于
GetInstance
根据声明只返回
object
,因此
Func
在这里完全正常。@HimBromBeere OP希望
myFunc
成为
Func
,而不是
Func
。他尝试使用
CreateDelegate
,但不起作用。但是,生成的委托不是强类型的,我认为OP实际上需要它。@HimBromBeere此委托将是强类型的,因为它的类型将与
typeof(Func)兼容。MakeGenericType(hiddenType)
。当然,它不是静态类型的委托(这是不可能的,因为类型是隐藏的)。谢谢!有一段时间我认为
Expression
可以做到这一点,但我不知道该怎么做。我认为问题在于
hiddenType
只在运行时才知道,因此静态绑定到通用包装器将不起作用。
GetTypedInstance<SomeClass>();
GetInstance(typeof(SomeClass));