[英]Interface as interface return type
在我的應用程序中,我使用不同的web api來獲取汽車信息。 對於我已經實現了ICarService的服務。 由於所有這些Api都返回了不同的汽車數據集,我已經實現了ICar接口,因此每個服務都可以返回自己的汽車類型,但在我的應用程序中我可以使用“通用”ICar。
這是我的實現:
// Car Model
public interface ICar
{
string Color { get; }
}
public class CarApiA : ICar
{
public int car_color { get; set; }
public Color
{
get { return this.car_color; }
}
}
// Service
public interface ICarService
{
Task<List<ICar>> GetCarsAsync(string search);
}
public class CarApiAService : ICarService
{
public async Task<List<CarApiA>> GetCarsAsync(string search)
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<CarApiA>>(content);
}
}
現在我收到錯誤消息“'CarApiAService'沒有實現接口成員'ICarService.GetCarsAsync(string)'。'CarApiAService.GetCarsAsync(string)'無法實現'ICarService.GetCarsAsync(string)',因為它沒有匹配的返回'System.Threading.Tasks.Task>'的類型。“
我如何使用界面返回界面? 如果我的實施想法完全錯誤,請指導我正確指導。
考慮使用IEnumerable
而不是IList
。 這允許您使用協變泛型類型:
public async Task<IEnumerable<ICar>> GetCarsAsync(string search)
{
// ...
return JsonConvert.DeserializeObject<List<CarApiA>>(content);
}
(當然界面也必須更新......)
public interface ICarService
{
Task<IEnumerable<ICar>> GetCarsAsync(string search);
}
如果您想知道與泛型類型的協方差,請解釋一下:
List<T>
這樣的通用接口) out
(即只讀),則接口只能是協變的。 這就是為什么IEnumerable<out T>
是協變的,但IList<T>
不是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.