简体   繁体   中英

Can not initialize irepository<> generic

I defined and implemented IRepository , IEntity code as below.

//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; }
}

when i try to create initialize a Repository<customer>()

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

I got this error:

'Infrastructure.Repository.Repository' to 'Infrastructure.Repository.IRepository'. An explicit conversion exists (are you missing a cast?)

But when i use code above, it works.

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

i thought IRepository<customer,int> is equal to IRepository<customer> What is the problem when initial a repository like this:

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

As mentioned by @Reasurria in the comments, your Repository<TEntity> class does not inherit from IRepository<TEntity> so the compiler cannot perform an implicit conversion between them. You need to update your class definition to include the missing interface:

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

I dont know if this can solve your problem: When i test your code like this

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

Casting to IRepository, the error has gone. Maybe the compiler don t know what to do because you have 2 declarations of Repository` class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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