无法传递实现接口的参数

时间:2017-07-02 16:44:49

标签: c# .net generics c#-4.0

情景:

public interface IEntity {
    int Id {get; set;};
}

public interface IRepository<T> where T: class, IEntity {
    //repo crud stuffs here
}

public class RepositoryBase<T> : IRepository<T> where T : class, IEntity {
    //general EF crud implementation
}

public class MyEntity : IEntity {
    //implementation and other properties
}

public interface IMyEntityRepository : IRepository<MyEntity> {
    //any extending stuff here
}

public class MyEntityRepository : RepositoryBase<MyEntity>, IMyEntityRepository {
    //implementation here
}

public interface IBusinessLogic<T> where T : class, IEntity {
}

public class BusinessLogicBase<T> : IBusinessLogic<T> where T : class, IEntity {
    private readonly IRepository<T> _baseRepo;
    private readonly IList<IRepository<IEntity> _repositories;

    public BusinessLogicBase(IRepository<T> baseRepo, params IRepository<IEntity>[] repositories) {
        _baseRepo = baseRepo;
        _repositories = repositories;
    }

    //some standard business logic methods that resolve the repositories based on navigation property types and call

    private IRepository<U> ResolveRepository<U>() where U: class, IEntity {
        IRepository<U> found = null;
        foreach (IRepository<IEntity> repository in _repositories) {
            if (repository.IsFor(typeof(U))) {
                found = repository as IRepository<U>;
                break;
            }
        }
        return found;
    }
}

public interface IMyEntityBL : IBusinessLogic<MyEntity> {
    //extended stuff here
}

public class SomeOtherEntity : IEntity {
}

public interface ISomeOtherEntityRepository : IRepository<SomeOtherEntity> {
}

public interface SomeOtherEntityRepository : RepositoryBase<SomeOtherEntity>, ISomeOtherEntityRepository {
}

public class MyEntityBL : BusinessLogicBase<MyEntity>, IMyEntityBL {
    public MyEntityBL(IRepository<MyEntity> baseRepo, ISomeOtherEntityRepository someOtherEntityRepo) : base(baseRepo, someOtherEntityRepo) {
        //ERROR IS HERE WHEN TRYING TO PASS ISomeOtherEntityRepository to base
    }
    //implementation etc here
}

为什么我不能将ISomeOtherEntityRepository传递给base?我得到“不可分配的参数类型”错误。它实现了IRepository,SomeOtherEntity是一个IEntity,所以我不明白为什么我尝试的是无效的。有人可以建议吗?

1 个答案:

答案 0 :(得分:1)

public interface IRepository<out T> 
   where T : class, IEntity

有关共方差和反方差的详细解释,请参阅this answer