Does anybody know how to dynamically create a Func<T>
instance?
//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
Anyone?
You need to use Expression trees:
var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();
I don't think you can. This blog goes some way to explaining the issue. I suggest you look for an alternative approach. Can you use expression trees instead?
You need a object which can be converted into System.Object
, for this you need to create a delegate like Func<String>
first. So it makes no sence for me to create the Func<T>
at runtime.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.