[英]Activator.CreateInstance - How to create instances of classes that have parameterized constructors
[英]Using Activator.CreateInstance to create Func<T> instances
有人知道如何动态创建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[]
类型,因为它不是委托类型
任何人?
您需要使用表达式树:
var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();
我认为你不能。 该博客以某种方式解释了该问题。 我建议您寻找一种替代方法。 您可以改用表达式树吗?
您需要一个可以转换为System.Object
的对象,为此,您需要首先创建一个类似于Func<String>
的委托。 因此,在运行时创建Func<T>
对我来说毫无意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.