簡體   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