[英]C# Pass Method as parameter with different parameters with Action and Func delegates
我的代码中有一个场景,我需要将方法作为参数传递给另一个调用的方法。
我的方法有不同的参数,返回类型也不同,
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;
}
以上方法需要从单独的方法调用
public void InvokeMethod(Action action){
action();
}
操作参数可以是方法 1 或方法 2,但问题是我如何获得方法 1 和方法 2 不同的返回类型。
如果我使用 Func,我将无法在运行时告诉输入参数的数量。
实际上,我尝试通过 wcf 通道上的包装器调用服务操作,以便我可以处理该方法中任何调用的任何异常...
例如: Channel.GetAllNames(int a,string b) 是一个实际调用。 这个调用应该通过一个通用的方法。CallAllOperations。
public void CallAllOperations(Action action){
try{
action();
}
catch(exception e){
//catch exceptions of all calls instead of one call.
}
}
您可以将委托包装在 lambda 中。 例如:
假设您创建了两个委托:
Func<DateTime> getTime = BuildGetTimeDelegate();
Func<int, int, int> getSum = BuildSumDelegate();
现在想在特定数据上使用它们:
DateTime time;
int sum;
int a = 5;
int b = 10;
你可以给你的 invoke 方法 lambdas:
InvokeMethod(()=>time = getTime());
InvokeMethod(()=>sum = getSum(a,b));
这意味着在将委托转换为 Action 时,您必须解析输入和输出变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.