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));