接受和返回不同泛型类型的最佳实践

问题描述 投票:0回答:1

如果标题不是最清楚地表达问题的方式,我深表歉意。下面的代码片段工作正常,但我想修改该方法以接受泛型类型和不同的类型作为第二个参数。我知道我可以在方法外部将对象序列化为 JSON 并传递字符串,或者使用动态类型作为第二个参数,但这两个选项似乎都不太正确

Severity    Code    Description Project File    Line    Suppression State
Error (active)  CS1503  Argument 2: cannot convert from 'LoginModel' to 'LoginAttemptModel'
var logginAttemptModel = await new RESTLibrary.RESTAction().PostTypeAsync<LoginAttemptModel>(loginRestInformation, loginModel);`

    public async Task<T> PostTypeAsync<T>(TInfo information, T model)
    {
        var json = JsonConvert.SerializeObject(model);
        using (var httpClient = GetHttpClient(information))
        {
            using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
            {
                using (var response = await httpClient.PostAsync(restInformation.Resource, content))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        return JsonConvert.DeserializeObject<T>(responseContent);
                    }
                    return default(T);
                }
    
            }
        }
    }
c#
1个回答
0
投票

要处理您想要接受两种不同类型作为参数(例如 LoginModel 和 LoginAttemptModel)的场景,您可以修改方法签名以允许第二个参数的灵活性,而不将两个参数限制为同一类型。一种常见的方法是让该方法接受两种泛型类型,TInfo 用于信息,TModel 用于模型,如下所示:

public async Task<T> PostTypeAsync<T, TModel>(TInfo information, TModel model)
{
    var json = JsonConvert.SerializeObject(model);
    using (var httpClient = GetHttpClient(information))
    {
        using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
        {
            using (var response = await httpClient.PostAsync(information.Resource, content))
            {
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<T>(responseContent);
                }
                return default(T);
            }
        }
    }
}

使用示例:

var logginAttemptModel = await new RESTLibrary.RESTAction()
    .PostTypeAsync<LoginAttemptModel, LoginModel>(loginRestInformation, loginModel);
© www.soinside.com 2019 - 2024. All rights reserved.