返回diff对象的方法的新关键字c#

时间:2015-02-22 23:33:37

标签: c#

我有以下方法继承

public class RepositoryBase<TEntityModel> : IRepository<TEntityModel>
    where TEntityModel : Entity
{
    public virtual IEnumerable<TEntityModel> GetAll()
    {

    }

}

public class Repository<TDomainModel, TEntityModel> : RepositoryBase<TEntityModel>, IRepository<TEntityModel>
    where TEntityModel : Entity
{
    public override IEnumerable<TDomainModel> GetAll() // --> the compiler complain to add "new" keyword, why ?
    {

    }
}

我知道方法签名是相同的,但它们都返回两个diff对象,所以编译器为什么抱怨应用&#34; new&#34; Repository类中GetAll方法的关键字?

如果上述方法被编译器抱怨,为什么以下不需要应用&#34; new&#34;关键字?

public class RepositoryBase<TEntityModel> : IRepository<TEntityModel>
    where TEntityModel : Entity
{
    public virtual void SomeMethod(TEntityModel model)
    {

    }

}

public class Repository<TDomainModel, TEntityModel> : RepositoryBase<TEntityModel>, IRepository<TEntityModel>
    where TEntityModel : Entity
{
    public override void SomeMethod(TDomainModel model) // --> this one needs no "new" keyword
    {

    }
}

1 个答案:

答案 0 :(得分:0)

因为你不能改变基本方法的返回类型。

E.g。这应该有效:

public override IEnumerable<TEntityModel> GetAll()

我想没有办法告诉编译器返回是协变的。

我可以问你想用TDOmainModel和TEntityModel实现什么,这样的事情不符合要求吗?为什么你需要它们作为单独的泛型?

public class RepositoryNew<TDomainModel> : RepositoryBase<TDomainModel>
    where TDomainModel : Entity
{
    public override IEnumerable<TDomainModel> GetAll() // --> the compiler complain to add "new" keyword, why ?
    {

    }
}

编辑这对我有用:

public class RepositoryBase<TEntityModel> : IEntityRepository<TEntityModel>
where TEntityModel : Entity
{
    public IEnumerable<TEntityModel> GetAll()
    {
        throw new NotImplementedException();
    }
}

public class Repository<TDomainModel, TEntityModel> : RepositoryBase<TEntityModel>, IDomainRepository<TDomainModel>
    where TEntityModel : Entity
{
    public new IEnumerable<TDomainModel> GetAll()
    {
        throw new NotImplementedException();
    }
}

用法:

        var repository = new Repository<Domain, Entity>();

        IEntityRepository<Entity> entityRepo = repository; // IMPORTANT! Casting to IEntityRepository
        IDomainRepository<Domain> domainRepo = repository; // IMPORTANT! Casting to IDomainRepository

        IEnumerable<Entity> entityModels = entityRepo.GetAll();
        IEnumerable<Domain> domainModels = domainRepo.GetAll();

        RepositoryBase<Entity> repository2 = new RepositoryBase<Entity>();

        IEnumerable<Entity> entityModels2 = repository2.GetAll();
  • 选项1 - 域不从实体继承:

    将该方法标记为new方法,因为它们返回完全不同的类型:|

  • 选项2 - 如果域:实体:

    RepositoryBase<TDomainModel>

  • 选项3 - 域:实体,您需要基本实体泛型类型,尽管您最好使用域

    public class RepositoryBase<TDomainModel, TEntityModel>