泛型基类的隐式引用转换复杂性错误

本文关键字:转换 复杂性 错误 引用 基类 泛型 | 更新日期: 2023-09-27 17:53:37

我希望能够创建以下类结构:

    public class Person
    {
        public Person() { }
        public string Name { get; set; }
    }
    class Student : Person { }
    class FireFighter : Person { }
    class PoliceOfficer : Person { }
    class Building<T> where T : Person, new()
    {
        public IEnumerable<T> Members { get; set; }
    }
    class School : Building<Student> { }
    class FireStation : Building<FireFighter> { }
    class PoliceStation : Building<PoliceOfficer> { }
    class Container<T> where T : Building<Person>, new() { }
    class SchoolDistrict : Container<School> { }

然而这给了我以下错误:

类型'School'不能用作泛型类型或方法'Container'中的类型参数'T'。没有从"学校"到"建筑"的隐含引用转换

我在这里做错了什么?

泛型基类的隐式引用转换复杂性错误

泛型类型不能满足您的需要。如上所述,Building<Person>不是Building<Student>。但是,对最后两个类的更新将允许编译:

    class Container<T, U> 
        where U : Person, new()
        where T : Building<U>, new() { }
    class SchoolDistrict : Container<School, Student> { }

SchoolBuilding<Student>。虽然StudentPerson,但Building<Student>不是Building<Person>

引入接口将允许您利用泛型声明中的协方差。这将允许建筑被视为建筑,这是你最终想要实现的。注意,只有接口通过'out'修饰符支持:

    public class Person
    {
        public Person() { }
        public string Name { get; set; }
    }
    class Student : Person { }
    class Building<T> : IBuilding<T>
        where T : Person, new()
    {
        public IEnumerable<T> Members { get; set; }
    }
    internal interface IBuilding<out TPerson> where TPerson : Person { }
    class School : Building<Student> { }
    class Container<T>
        where T : IBuilding<Person>, new() { }
    class SchoolDistrict : Container<School> { }