2013-10-10 156 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

我不知道为什么这是投票。 –

相关问题