使用Activator.CreateInstance创建Func<T>实例

9

有人知道如何动态创建Func<T>实例吗?

//Create the Func type

Type funcType = typeof(Func<>).MakeGenericType(typeof(string)); 

//How do I pass a reference to the anonymous method? 

Activator.CreateInstance(funcType, () => "test");

代码无法编译:

不能将lambda表达式转换为类型object[],因为它不是委托类型。

有人能解决吗?


5
为了更有可能得到答案,您应该尝试描述您想要实现什么,而不是如何实现它。 - Jamiec
我同意Jamiec的观点,因为在这种情况下,通常Expression命名空间比硬核反射更好。 - SWeko
seesharper,您能否请看一下这个关于LightInject的注入问题?https://dev59.com/i3fZa4cB1Zd3GeqPNRrC - JK.
3个回答

3
您需要使用表达式树(Expression Trees):
var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();

1

我认为你做不到。这篇博客在一定程度上解释了这个问题。我建议你寻找另一种方法。你能用表达式树吗?


0
你需要一个可以转换为 System.Object 的对象,因此你需要首先创建像 Func<String> 这样的委托。所以对我来说,在运行时创建 Func<T> 没有意义。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接