可以由调用者自定义的通用谓词?

A generic predicate which can be customized by caller?

我有一堆这样定义的谓词,每个都检查不同的 http 状态代码:

readonly Predicate<HttpResponseData> createdHttpStatusPredicate = (HttpResponseData responseData) => {
    return responseData.StatusCode == HttpStatusCode.Created;
};

readonly Predicate<HttpResponseData> okHttpStatusPredicate = (HttpResponseData responseData) => {
    return responseData.StatusCode == HttpStatusCode.OK;
};

...

我像这样将它们传递给以下方法(代码已经简化了一点以删除不相关的细节):

public static async Task<HttpResponseData> HttpCaller(HttpMethod requestMethod, Predicate<HttpResponseData> predicate)
{
    HttpResponseData response = await SendHttpRequest(requestMethod);

    if (predicate(response) == true)
        return response;
    else
        return null;
}

这是一个示例调用,将一个谓词发送到上述方法中:

HttpResponseData data = await HttpRequestUtils.HttpCaller(HttpMethod.Post, createdHttpStatusPredicate);

我想知道,我能否将所有谓词组合到某个通用谓词中,或者在我调用 HttpCaller 时以某种方式指定要在谓词中查找的 http 状态?

是的,我知道上面的例子没有多大意义,因为我可以直接将我正在寻找的 http 状态传递给 HttpCaller 而无需通过谓词,但在我的例子中 HttpCaller 也可以接收我的复杂谓词作为输入,这取决于从

调用 HttpCaller 的位置

接下来的两种方法可以用来摆脱所有只检查 HttpStatusCode.

的谓词

1。创建一个方法,为给定的 HttpStatusCode:

创建一个 Predicate
public static Predicate<HttpResponseData> CreatePredicateByHttpStatusCode(HttpStatusCode status)
{
    return r => r.StatusCode == status;
}

然后在需要仅检查给定 HttpStatusCode:

Predicate 时使用此方法
var result = await HttpCaller(httpMethod, CreatePredicateByHttpStatusCode(HttpStatusCode.OK));

2。创建方法 HttpCaller 的重载,它接受 HttpStatusCode 并且只检查给定的 HttpStatusCode:

// This is your current method. It accepts a common Predicate that is used
// to check for complex conditions.
public static async Task<HttpResponseData> HttpCaller(HttpMethod requestMethod, Predicate<HttpResponseData> predicate)
{
    HttpResponseData response = await SendHttpRequest(requestMethod);

    if (predicate(response) == true)
        return response;
    else
        return null;
}

// This is a new Method. It accepts HttpStatusCode instead of the Predicate.
// It can be used for checking only for HttpStatusCode.
public static async Task<HttpResponseData> HttpCaller(HttpMethod requestMethod, HttpStatusCode status)
{
    // Here your original method HttpCaller is used.
    return await HttpCaller(requestMethod, r => r.StatusCode == status);
}

当您只需要检查 HttpStatusCode:

时,可以使用 HttpCaller 的重载形式
var result = await HttpCaller(httpMethod, HttpStatusCode.OK);