C#传递方法作为带有Action和Func委托的不同参数的参数
问题描述:
我在我的代码中有一个场景,我需要将方法作为参数传递给另一个调用的方法。C#传递方法作为带有Action和Func委托的不同参数的参数
我的方法有不同的参数和返回值类型也不同,
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一个,串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方法lambda表达式:
InvokeMethod(()=>time = getTime());
InvokeMethod(()=>sum = getSum(a,b));
这意味着您必须在将委托转换为Action时解析输入和输出变量。
我们在这里错过了一些背景。你想达到什么目的?用例是什么? –
如果你想在运行时创建不同的委托,请看https://stackoverflow.com/a/9507589/5794617 –
好的,假设你创建了一个包含10个委托的列表。接下来你要做什么?答案很大程度上取决于这一点。 –