从“派生类型”到“派生类型”没有隐式引用转换.到“基本类型”;在泛型

本文关键字:类型 派生 派生类型 基本类型 泛型 引用 转换 | 更新日期: 2023-09-27 18:14:19

代码

 public interface IEntity<T>  
   {
       T Id { get; set; }
   }

public abstract class Entity<T> : IEntity<T>       
    {
        public T Id { get; set; }
    }
 public class Country : Entity<int>
    {
...
    }
 public interface IRepository<T> where T : Entity<Type>
    {
    }
 public abstract class Repository<T> : IRepository<T>
       where T : Entity<Type>
    {
    }
 public class CountryRepository : Repository<Country>
{
}

我得到以下错误:

类型"模型"。Country'不能用作泛型类型或方法'Repository'中的类型参数'T'。没有从"国家"到"实体"的隐式引用转换。

如何将派生类型映射为基类型作为泛型参数?

编辑:

我在这里通过创建一个基类并使用它得到了我的解决方案。

http://msdn.microsoft.com/en-us/library/aa479858.aspx

主持人可以删除这个问题

从“派生类型”到“派生类型”没有隐式引用转换.到“基本类型”;在泛型

您违反了通用约束:

public abstract class Repository<T> : IRepository<T>
   where T : Entity<Type> // <= here

public class Country : Entity<int>

Entity<int>不是Entity<Type>

如果你想允许"任意类型",你可以通过一个公共基类来实现:

public abstract class Entity { }
public abstract class Entity<T> : Entity, IEntity<T>       
{
    public T Id { get; set; }
}
public abstract class Repository<T> : IRepository<T>
   where T : Entity
{
}