我想创建一些通用方法,如下面的代码:
public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>
显然我想支持可枚举集合以及从IBaseModel
接口(interface)驱动的单个对象。
方法定义没问题,但是当涉及到它的使用时,我会收到以下错误:
await myClass.Get<List<DrivedClassFromBaseModel>>("some url");
There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"
最佳答案
Generic constraints将通过 AND 组合,因此 where T : IBaseModel, IList<IBaseModel>
意味着 T
应该同时实现 IBaseModel
和IList<IBaseModel>
.
您需要创建两个方法:
public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel
关于c# - 通过特定的 where 子句在 C# 中创建通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53977528/