()...">

Restrictions Accepting Both Types in Generics

In generics, we can give constraints using a < where " clause like

public void MyGeneric <T> () where T: MyClass1 {...}

Now, if I want type T to have type MyClass1 and say IMyInterface, then I need to do something like

public void MyGeneric <T> () where T: MyClass1, IMyInterface {...}

But I do not know (or perhaps this is impossible) if we can create a general method that can accept types that inherit from either of the two types. those. if any of my other classes inherits from MyClass1 or implements IMyInterface, but none of my classes have both, then my general method should work for these classes.

I hope I get it.

+3
source share
7 answers

You cannot and for good reason. Suppose MyClass1 and IMyInterface have a CoolThing () method (presumably such a commonality is exactly why you want to do such things in the first place). You kind of want code like:

public void MyGeneric<T>(T item) where T : MyClass1 or T : IMyInterface
{
  item.CoolThing();
}

, MyClass1.CoolThing() - IMyInterface.CoolThing(). , , (Employee.Fire(), -, Gun.Fire() ..).

, . - . , , MyClass1 IMyInterface.

- MethodInfo , "CoolThing" , . , , .

+5

, , .

, . , - .

:

class MyClass1 : IAllowInMyGeneric { ... }
interface IMyInterface : IAllowInMyGeneric { ... }

public void MyGeneric <T>() where T : IAllowInMyGeneric {...}
+3

, . where T : MyClass1, IMyInterface - .

.

+2

:

interface IFoo { void A(); }
interface IBar { void B(); }

class Test<T> where T Ifoo <OR> IBar
{
    void M() {  T.A(); } // will this work?? 
}

, . .

+1

- , .

0

0

Unfortunately, this is impossible to do. To make this work MyClass1, you need to implement it IMyInterface. In this case, you probably don't need generics because of the common interface.

0
source

Source: https://habr.com/ru/post/1759131/


All Articles