簡體   English   中英

C# 傳遞方法作為參數,具有不同參數的 Action 和 Func 委托

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM