Interfaces inheritance in C#

吃可爱长大的小学妹 提交于 2019-12-03 11:59:25

In .NET 3.5 you definitely can't treat an IRepository<Book> as an IRepository<IRepoItem>.

We'd need to know more about what you're using the repository for in RepositoryManager to really know how to solve it... but could you create a non-generic IRepository interface which IRepository<T> extends? Make it include all the members which don't refer to T. Then you can declare currentRepo as just an IRepository.

Try using the intermediate layer (IRep):

    interface IRepository<T>
    {
    }

    interface IRep<T> : IRepository<IRepoItem> where T : IRepoItem
    {
    }

    interface IBookRepository : IRep<Book>
    {
    }

    class BookRepository : IBookRepository
    {
    }

then you can do what you want:

        BookRepository br = new BookRepository();
        IRepository<IRepoItem> currentRepo = br;

In .NET 3.5 there isn't any relation between IRepository and IRepository in .NET 4, you could achieve something like this with covariance and contravariance support (but it depends on the IRepository interface declaration)

A would recommand using a non generic IRepository interface and doing the cast yourself. I know, it's not wonderful, but the fonctionality you describe requires covariance/contravariance support.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!