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?
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 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 {
...
}
Are you asking how to express this structure in C#? If so below one example:
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
{
}
ChildPerson
class for illustration. Maybe just for clarity add a note that you only added that class for illustration; it's not required for the requested functionality? –
Maribeth In case an interface shall be applied as well:
public class ChildClass<T> : BaseClass where T : class, IInterface
There is no multiple inheritance in C#, therefore you cannot enforce that a type inherits from multiple classes.
Sounds like your structure is incorrect.
To ensure both are implement, either one of them has to be an interface, or one of them has to implement the other.
If you mean T can implement B or Person then, then there should be some abstract base class/interface that B and Person share which you restrict to that
© 2022 - 2025 — McMap. All rights reserved.