我是泛型新手,我正在尝试为我的项目创建一个通用的 HTTP GET 方法(并可能将其扩展以处理 POST/PUT)。当响应基于字符串时,以下内容似乎可以正常工作:
private async Task<T> HttpGetAsync<T>(Uri uri)
{
var httpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = uri,
Headers =
{
{ "Authorization", $"Basic {encodedCredentials}"},
{ "Cache-Control", "no-cache" }
}
};
var response = await _httpClient.SendAsync(httpRequestMessage);
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
但在某些情况下,根据类型,我希望使用 ReadAsByteArrayAsync() 或 ReadAsStreamAsync() 而不是 ReadAsStringAsync() 读取响应。
我认为我可以在方法中执行 getType() ,并使用适当的方法读取响应,但我想知道是否有更好的方法来做到这一点?
这是一个坏主意/泛型的错误用法吗?感谢您提供任何信息!
最佳答案
使用接口(interface):
interface IContentReader<T>
{
T ReadAsync(HttpResponseMessage response);
}
private async Task<T> HttpGetAsync<T>(Uri uri, IContentReader<T> reader)
{
var httpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = uri,
Headers =
{
{ "Authorization", $"Basic {encodedCredentials}"},
{ "Cache-Control", "no-cache" }
}
};
var response = await _httpClient.SendAsync(httpRequestMessage);
return await reader.ReadAsync(response);
}
并且您可以有 IContentReader<T>
的不同实现。
您可以根据 T
确定使用哪个实现.
关于C# 和泛型 : how can I handle processing based on type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60755897/