【发布时间】:2015-06-18 13:09:55
【问题描述】:
我在变量中指定了类型: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,并且无法更改签名。
【问题讨论】:
-
我看不到您想要实现的目标。由于
GetInstance根据声明仅返回object,因此Func<object>在这里绝对可以。 -
@HimBromBeere OP 希望
myFunc成为Func<HiddenType>,而不是Func<object>。他尝试使用CreateDelegate,但没有成功。
标签: c# reflection delegates