Call Func <int, bool> by reflection

I want to save lambdas as objects and execute them later using reflection. Regardless of the merits of doing this, I wonder how to get something like the following.

Say I have different functions defined as

Func<string,bool> f1 = (i)=>i == "100"; Func<int,bool> f2 = (i)=>i == 100; 

Is it possible to execute them at runtime if I get all types involved at runtime (I cannot pass a Func object, etc., because I don't know what types are involved), can I do something like next?

 void RunFunc(Type param1, Type returnParam, object obj) { Type funcType = typeof(Func<,>).MakeGenericType(param1,returnParam); var d = Delegate.CreateDelegate(funcType , obj,"Invoke"); d.DynamicInvoke(); } 

thanks

+4
source share
1 answer

Sure. You just need to call DynamicInvoke , specifying a parameter of the appropriate type.

But why bother? You can make it much easier

 Delegate del; del = f1; var result1 = del.DynamicInvoke("99"); del = f2; var result2 = del.DynamicInvoke(100); 

You can specify any of them in the Delegate , and you don’t even need to know the types of arguments or the return value to call them (just the number of arguments). Of course, you will need to know the type of the return value at some point in order to use it, but that’s it.

+5
source

Source: https://habr.com/ru/post/1344945/


All Articles