[英]C# Generics How Can I get the type passed as an argument for a generic method with no object type as a parameter?
[英]C# and Generics: how can I handle processing based on type?
我是泛型的新手,我正在嘗試為我的項目創建一個通用的 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 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
確定要使用的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.