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.
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" , . , , .