代码之家  ›  专栏  ›  技术社区  ›  RA.

C中的条件类型参数#

  •  0
  • RA.  · 技术社区  · 6 年前

    我想将对象反序列化为给定的类类型,这取决于ajax响应是否成功。

    所以我写了下面的方法:

    public IAjaxResponse GetResponse<TOk, TFail>()
    {
        var responseJson = this.response as Dictionary<string, object>;
    
        object obj = null;
    
        if ((string)responseJson["status"] == "ok")
            obj = JsonConvert.DeserializeObject<TOk>(responseJson);
        else
            obj = JsonConvert.DeserializeObject<TFail>(responseJson);
    
        return (IAjaxResponse)obj;
    }
    

    现在很容易使用:

    var response = GetResponse<ClassWhenOk, ClassWhenFail>();
    if (response is ClassWhenFail responseFail) {
        Error.Show(responseFail.message);
        return;
    }
    [..]
    

    现在我的问题是 :有时,有些泛型响应总是“正常”状态,因此我不想对失败状态使用第二个类型参数。

    所以我想用这样的东西:

                   \/ notice one type argument
    GetResponse<ClassWhenOk>();
    

    但这是不允许的,因为使用此泛型方法需要2个类型参数。

    所以我的问题来了 :

    我能记下第二个类型参数吗( TFail )作为“不需要”?还是我应该采取不同的方法?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Enigmativity    6 年前

    你的代码没有意义。这个 responseJson 对象不能是 Dictionary<string, string> 和A string 同时。能够发布真正的代码供我们工作是件好事。

    下面是一个重构的例子,它确实可以编译,但是需要一些工作才能在运行时正常运行。尽管如此,你所需要的只是一个替代的过载来让它工作。

    public IAjaxResponse GetResponse<TOk, TFail>(string response)
    {
        var responseJson = new Dictionary<string, object>();
    
        object obj = null;
    
        if ((string)responseJson["status"] == "ok")
            obj = Newtonsoft.Json.JsonConvert.DeserializeObject<TOk>(response);
        else
            obj = Newtonsoft.Json.JsonConvert.DeserializeObject<TFail>(response);
    
        return (IAjaxResponse)obj;
    }
    
    public IAjaxResponse GetResponse<TOk>(string response)
    {
        return (IAjaxResponse)Newtonsoft.Json.JsonConvert.DeserializeObject<TOk>(response);
    }
    

    第二种方法甚至可以是:

    public IAjaxResponse GetResponse<TOk>(string response)
    {
        return GetResponse<TOk, FailDontCare>(response);
    }
    

    这样就避免了代码重复。