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

see*_*per 8 c#

有人知道如何动态创建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");
Run Code Online (Sandbox Code Playgroud)

这不编译:

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

任何人?

Myl*_*ell 1

我认为你不能。这篇博客在某种程度上解释了这个问题。我建议您寻找替代方法。你可以使用表达式树来代替吗?