传递回调方法作为参数

时间:2013-10-10 07:58:16

标签: c#

我想将一个回调方法作为参数传递给一般化方法,但无法弄清楚如何做到这一点。我尝试使用Func<IAsyncResult>,但它似乎不兼容。

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

回调的签名是:

void GetRequestStreamCallback(IAsyncResult asyncResult)

2 个答案:

答案 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

     

封装具有单个参数但不返回的方法   价值。

答案 1 :(得分:1)

BeginGetRequestStream需要一个AsyncCallback类型的参数。因此,将callback参数声明为该类型。

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

然后,您可以传递回调方法,因为它与所需的签名匹配。

webRequest(apiName, requestMethod, requestData,
    GetRequestStreamCallback);