【发布时间】:2017-10-13 10:00:41
【问题描述】:
我的代码中有一个场景,我需要将方法作为参数传递给另一个调用的方法。
我的方法参数不同,返回类型也不同,
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();
}
Action 参数可以是 method1 或 method2,但问题是如何获得 method1 和 method2 不同的返回类型。
如果我使用 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.
}
}
【问题讨论】:
-
我们在这里错过了一些上下文。你想达到什么目的?用例是什么?
-
如果您想在运行时创建不同的委托,请查看stackoverflow.com/a/9507589/5794617
-
好的,假设您创建了一个包含 10 个代表的列表。你接下来要做什么?答案很大程度上取决于此。
-
实际上,我尝试通过 wcf 通道上的包装器调用服务操作,以便我可以处理该方法中任何调用的任何异常...例如: Channel.GetAllNames(int a,string b ) 是一个实际的调用。此调用应通过一个通用方法。称为 CallAllOperations。 public void CallAllOperations(Action action){ try{ action(); } catch(exception e){ //捕获所有调用的异常,而不是一个调用。 } }