有人知道如何动态创建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[]
类型,因为它不是委托类型
任何?
答案 0 :(得分:3)
您需要使用表达式树:
var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();
答案 1 :(得分:1)
我认为你不能。 This blog在某种程度上解释了这个问题。我建议你寻找另一种方法。你可以使用表达式树吗?
答案 2 :(得分:0)
您需要一个可以转换为System.Object
的对象,为此您首先需要创建一个像Func<String>
这样的委托。因此,我无需在运行时创建Func<T>
。