我想创建一些通用方法,例如下面的代码:
public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>
很显然,我想支持可枚举的集合以及从IBaseModel
接口驱动的单个对象。
方法定义是可以的,但是使用它时,我会得到以下错误:
await myClass.Get<List<DrivedClassFromBaseModel>>("some url");
There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"
答案 0 :(得分:5)
通用约束将由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
答案 1 :(得分:0)
您可以使用另一个实现IBaseModel和IList的类,然后将T约束到该类。
public class DerivedModel : IBaseModel, IList<IBaseModel>
{
private int _size;
private IBaseModel[] _items=new IBaseModel[1000];
private int _version;
public int Id { get; set; }
public IEnumerator<IBaseModel> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
...
}
通用方法是:
public async Task<T> Get<T>(string url) where T : DerivedModel
{
return await Task<T>.Factory.StartNew(() =>
{
var derivedModel = new DerivedModel() {new BaseModel() {Id = 1}};
return (T) derivedModel;
});
}
IBaseModel和BaseModel可以位于其中:
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel : IBaseModel
{
public int Id { get; set; }
}
用法:
var inheritance=new Inheritance();
var result = await inheritance.Get<DerivedModel>("aaa");
textBox1.Text = result[0].Id.ToString();