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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With