【问题标题】:C# Pass Method as parameter with different parameters with Action and Func delegatesC# 将方法作为参数传递给具有不同参数的 Action 和 Func 委托
【发布时间】: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){ //捕获所有调用的异常,而不是一个调用。 } }

标签: c# wcf delegates


【解决方案1】:

您可以将您的委托包装在 lambda 中。例如:

假设你创建了两个委托:

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

现在想在特定数据上使用它们:

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

你可以给你的调用方法 lambdas:

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

这意味着您必须在将委托转换为 Action 时解析输入和输出变量。

【讨论】:

  • 我如何解析输入和返回值,invokemethod 有什么作用..我的意思是我在哪里调用它?
  • InvokeMethod 是你的方法,所以我希望你知道在哪里调用它......输入和输出值也是如此。如果您不知道,当您进行通话或将数据放入其中时,您提出问题的目的是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 2011-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多