简体   繁体   English

通过反射调用Func <int,bool>

[英]invoke a Func<int,bool> by reflection

I want to store lambdas as objects and execute them later using reflection. 我想将lambda作为对象存储,然后使用反射执行它们。 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 ? 如果我在运行时获得所有类型,我可以在运行时执行这些(我不能将对象强制转换为Func等因为我不知道涉及哪些类型),我可以执行以下操作吗?

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 谢谢

Sure you can. 你当然可以。 You just need to call DynamicInvoke while providing a parameter of the appropriate type. 您只需在提供相应类型的参数时调用DynamicInvoke

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). 您可以将其中任何一个转换为Delegate ,甚至不需要知道参数的类型或返回值来调用它们(只是参数的数量)。 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. 当然,你需要在某个时候知道返回值的类型才能使用它,但这就是它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM