开发者

invoke a Func<int,bool> by reflection

I want to store lambdas as objects and execute them later using reflection. Irrespective of the merits of doing it this way, I wonder how to get something like the following working.

Say I have different functions defined as -

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

Can I then execute these at runtime if I get all the types involved at runtime (I cannot cast the object to Func etc. because I do not know what types are involved ), Can I do something like the following ?

void RunFunc(Type param1, Type returnParam, object obj)
{
   Type funcType = typeof(Func<,>).MakeGenericType(param1,return开发者_开发百科Param);
   var d = Delegate.CreateDelegate(funcType , obj,"Invoke");
   d.DynamicInvoke();
}

Thanks


Sure you can. You just need to call DynamicInvoke while providing a parameter of the appropriate type.

But why bother? You can do the much simpler

Delegate del;

del = f1;
var result1 = del.DynamicInvoke("99");

del = f2;
var result2 = del.DynamicInvoke(100);

You can cast any one of those to Delegate, and you don't even need to know the types of the arguments or the return value to call them (just the number of the arguments). Of course you 'll need to know the type of the return value at some point to use it, but that's just about it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜