我想将一个回调方法作为参数传递给一般化方法,但无法弄清楚如何做到这一点。我尝试使用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
实例:
封装没有参数并返回值的方法
TResult
参数指定的类型。
Action<T>
不会返回任何内容,只需参数:
封装具有单个参数但不返回的方法 价值。
答案 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);