简体   繁体   中英

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.

if i use Func i will not be able to tell the number of input parameters at runtime.

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...

for example : Channel.GetAllNames(int a,string b) is a actual call. this call should go through a generic method.called 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. 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:

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

This means you have to resolve input and output variable when converting your delegate into Action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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