繁体   English   中英

无法初始化 irepository<> 泛型

[英]Can not initialize irepository<> generic

我定义并实现了IRepositoryIEntity代码如下。

//define Repository
public interface IRepository {}
public interface IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey>
{
    TEntity Insert(TEntity entity);
}
public interface IRepository<TEntity> : IRepository<TEntity, int> where TEntity : class, IEntity<int> { }
public class Repository<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey>
{
    public TEntity Insert(TEntity entity)
    {
        return entity;
    }
}
public class Repository<TEntity> : Repository<TEntity, int> where TEntity : class, IEntity<int> { }
public interface IEntity<TPrimaryKey>
{
    TPrimaryKey Id { get; set; }
}

//define entity
public interface IEntity : IEntity<int> { }
public abstract class Entity : Entity<int>, IEntity { }
public abstract class Entity<TPrimaryKey> : IEntity<TPrimaryKey>
{
    public virtual TPrimaryKey Id { get; set; }
}

//customer
public class Customer : Entity
{
    public string Name { get; set; }
}

当我尝试创建初始化Repository<customer>()

IRepository<Customer> repository = new Repository<Customer>();

我收到此错误:

'Infrastructure.Repository.Repository' 到 'Infrastructure.Repository.IRepository'。 存在显式转换(您是否缺少演员表?)

但是当我使用上面的代码时,它起作用了。

IRepository<Customer,int> repository = new Repository<Customer>();

我认为IRepository<customer,int>等于IRepository<customer>初始化这样的存储库时有什么问题:

IRepository<Customer> repository = new Repository<Customer>();

正如@Reasurria 在评论中提到的,您的Repository<TEntity>类不是从IRepository<TEntity>继承的,因此编译器无法在它们之间执行隐式转换。 您需要更新类定义以包含缺少的接口:

public class Repository<TEntity> : Repository<TEntity, int>, IRepository<TEntity> where TEntity : class, IEntity<int> { }

我不知道这是否可以解决您的问题:当我像这样测试您的代码时

IRepository<Customer> repository =(IRepository<Customer>) new Repository<Customer>();

投射到 IRepository,错误消失了。 也许编译器不t know what to do because you have 2 declarations of Repository` 类的t know what to do because you have 2 declarations of

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM