您可以使用另一个同时实现 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();