2

我想创建一些通用方法,如下面的代码:

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>"
4

2 回答 2

5

通用约束将由 AND 组合,因此where T : IBaseModel, IList<IBaseModel>手段T应同时实现IBaseModeland 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
于 2018-12-30T12:42:51.293 回答
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();
于 2018-12-31T04:12:55.727 回答