[英]Using Activator.CreateInstance to create Func<T> instances
Does anybody know how to dynamically create a Func<T>
instance? 有人知道如何动态创建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");
This does not compile: 这不会编译:
Cannot convert lambda expression to type
object[]
because it is not a delegate type 无法将Lambda表达式转换为object[]
类型,因为它不是委托类型
Anyone? 任何人?
You need to use Expression trees: 您需要使用表达式树:
var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();
You need a object which can be converted into System.Object
, for this you need to create a delegate like Func<String>
first. 您需要一个可以转换为System.Object
的对象,为此,您需要首先创建一个类似于Func<String>
的委托。 So it makes no sence for me to create the Func<T>
at runtime. 因此,在运行时创建Func<T>
对我来说毫无意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.