I have this scenario:
class A<T>
I want a constrain of type Person like
class A<T> where T: Person
and I want A to inherit from B too.
example:
class A<T> : B : where T: Person
or
class A<T> where T: Person, B
how can I do it?
You cannot inherit a generic type. // class Derived20 : T {}// NO!
Multiple interface constraints can be specified. The constraining interface can also be generic.
4/7 Generics Constraints. Previous: Next: Generics Interfaces. Constraints are like rules or instructions to define how to interact with a generic class or method. They can restrict the parameter that will be replaced with T to some certain type or class or have some properties, like to be new instance of class.
class A<T> : B where T : Person
You can't inherit from more than one class in C#. So you can have
A<T>
inherites from B
and T
is Person
(Person
is either class or interface):
class A<T>: B where T: Person {
...
}
A<T>
doesn't necessary inherites from B
; but T
inherites from B
and implements Person
(Person
can be interface only):
class A<T> where T: Person, B {
...
}
It seems that you want case 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 {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With