2013-10-10 52 views
2

我想將回調方法作爲參數傳遞給廣義方法,但無法弄清楚如何執行它。我試過Func<IAsyncResult>,但它似乎並不兼容。回調的傳遞迴調方法作爲參數

public void webRequest(string apiName, string requestMethod, string requestData, Func<IAsyncResult> callback) 
{ 
    ... 
    request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request); 
} 

簽名是:

void GetRequestStreamCallback(IAsyncResult asyncResult) 
+0

不要說「不行」。告訴我們你的期望,以及實際發生的情況。 –

回答

4

聲明參數作爲Action<T>而不是Func<T>

public void webRequest(string apiName, string requestMethod, string requestData, Action<IAsyncResult> callback) 

Func<IAsyncResult>需要一個函數不帶參數,並返回IAsyncResult實例:

Func<TResult> Delegate

封裝沒有參數的方法,並返回該TResult指定的 類型值參數。

Action<T>不返回任何東西,只是需要參數:

Action<T> Delegate

封裝有一個參數,不返回 值的方法。

+0

再次查看代碼。回調參數未使用。你爲什麼在這裏推薦Action(T)?當然,AsyncCallback是所需的類型。 –

1

BeginGetRequestStream需要AsyncCallback類型的參數。所以聲明回調參數是那種類型。

public void webRequest(string apiName, string requestMethod, 
    string requestData, AsyncCallback callback) 
{ 
    ... 
    request.BeginGetRequestStream(callback, request); 
} 

然後,您可以傳遞您的回調方法,因爲它符合所需的簽名。

webRequest(apiName, requestMethod, requestData, 
    GetRequestStreamCallback); 
+0

我不知道爲什麼這是投票。 –