我有这样的场景:
class A<T>
我想要像
这样的 Person 类型的约束class A<T> where T: Person
我也希望 A 继承 B。
示例:
class A<T> : B : where T: Person
或
class A<T> where T: Person, B
我该怎么做?
class A<T> : B where T : Person
您不能从 C# 中的多个类继承。这样你就可以拥有
A<T>
继承自B
并且T
是Person
(Person
是class或interface):
class A<T>: B where T: Person {
...
}
A<T>
不一定继承自B
;但T
继承自B
并实现Person
(Person
只能是接口):
class A<T> where T: Person, B {
...
}
看来你想要的是情况1:
// A<T> inherites from B;
// T is restricted as being Person (Person is a class or interface)
class A<T>: B where T: Person {
...
}
你是想问如何在C#中表达这个结构吗?如果是这样,下面是一个例子:
class Program
{
static void Main(string[] args)
{
B a1 = new A<Person>();
B a2 = new A<ChildPerson>();
}
}
class Person
{
}
class ChildPerson : Person
{
}
class A<T> : B where T: Person
{
}
class B
{
}
C# 中没有多重继承,因此不能强制一个类型继承多个类。
听起来你的结构不正确。
为了确保两者都实现,其中之一必须是接口,或者其中之一必须实现另一个。
如果你的意思是 T 可以实现 B 或 Person,那么应该有一些 B 和 Person 共享的抽象基类/接口,你对此进行限制
如果还应应用接口:
public class ChildClass<T> : BaseClass where T : class, IInterface