泛型基的隐式引用转换编译错误 class
Implicit Reference Conversion Compliation Error with Generic Base class
我希望能够创建以下 class 结构:
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'。没有从 'School' 到 'Building'
的隐式引用转换
我做错了什么?
School
是一个 Building<Student>
。 Building<Student>
不是 Building<Person>
,尽管 Student
是 Person
。
通用类型无法满足您的需要。就像声明的那样; Building<Person>
不是 Building<Student>
。但是,这次对最后两个 类 的更新将允许编译:
class Container<T, U>
where U : Person, new()
where T : Building<U>, new() { }
class SchoolDistrict : Container<School, Student> { }
引入接口将使您能够在泛型声明中利用协变。这将使 Building 被视为 Building,这最终是您想要实现的目标。请注意,只有接口通过 '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> { }
我希望能够创建以下 class 结构:
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'。没有从 'School' 到 'Building'
的隐式引用转换我做错了什么?
School
是一个 Building<Student>
。 Building<Student>
不是 Building<Person>
,尽管 Student
是 Person
。
通用类型无法满足您的需要。就像声明的那样; Building<Person>
不是 Building<Student>
。但是,这次对最后两个 类 的更新将允许编译:
class Container<T, U>
where U : Person, new()
where T : Building<U>, new() { }
class SchoolDistrict : Container<School, Student> { }
引入接口将使您能够在泛型声明中利用协变。这将使 Building 被视为 Building,这最终是您想要实现的目标。请注意,只有接口通过 '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> { }