简体   繁体   English

C# 传递方法作为参数,具有不同参数的 Action 和 Func 委托

[英]C# Pass Method as parameter with different parameters with Action and Func delegates

I have a scenario in my code where i need to pass method as parameter to another methods which invokes.我的代码中有一个场景,我需要将方法作为参数传递给另一个调用的方法。

My method has different parameters and return type also varies,我的方法有不同的参数,返回类型也不同,

Public int Method1(int a, int b){
 return a+b;

}

public DataSet Method2(int a, string b, sting c, DataSet ds){
//make call to database and get results in dataset.
DataSet ds = new DataSet();
return ds;
}

The above methods needs to be call from separate method以上方法需要从单独的方法调用

public void InvokeMethod(Action action){
   action();
}

Action parameter can be method1 or method2 but the problem is how can i get return types which are different for method1 and method2.操作参数可以是方法 1 或方法 2,但问题是我如何获得方法 1 和方法 2 不同的返回类型。

if i use Func i will not be able to tell the number of input parameters at runtime.如果我使用 Func,我将无法在运行时告诉输入参数的数量。

Actually, I am try to call service operations through wrapper on wcf channel so that i can handle any exceptions of any call in that method...实际上,我尝试通过 wcf 通道上的包装器调用服务操作,以便我可以处理该方法中任何调用的任何异常...

for example : Channel.GetAllNames(int a,string b) is a actual call.例如: Channel.GetAllNames(int a,string b) 是一个实际调用。 this call should go through a generic method.called CallAllOperations.这个调用应该通过一个通用的方法。CallAllOperations。

public void CallAllOperations(Action action){
try{ 
action();
}
catch(exception e){
//catch exceptions of all calls instead of one call.
}
}

You can wrap your delegate in a lambda.您可以将委托包装在 lambda 中。 For instance:例如:

Suppose you create two delegate:假设您创建了两个委托:

Func<DateTime> getTime = BuildGetTimeDelegate();
Func<int, int, int> getSum = BuildSumDelegate();

And now want to use them on specific data:现在想在特定数据上使用它们:

DateTime time;
int sum;
int a = 5;
int b = 10;

You can give your invoke method lambdas:你可以给你的 invoke 方法 lambdas:

InvokeMethod(()=>time = getTime());
InvokeMethod(()=>sum = getSum(a,b));

This means you have to resolve input and output variable when converting your delegate into Action.这意味着在将委托转换为 Action 时,您必须解析输入和输出变量。

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

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