Generating non-generic class to base generic class

I usually use interfaces or base classes as parameter types when passing derived objects to a method. for example

Method1(ICar car);
Method2(BaseClass derivedClass);

But what about a base base class when the descendant class is not common?

public class GenericBaseClass<T> where T : BaseClass
{}

public class GenericDerivedClass1 : GenericBaseClass<DerivedClass1>
{}

I can write something like

Method3(GenericBaseClass<BaseClass> class);

but I cannot pass an object of type to this method am GenericDerivedClass1.

Is there any way to pass my descendant class to this method?

+3
source share
2 answers

You need to create your general Method3 method:

private void Method3<T>(GenericBaseClass<T> baseClass)
{

}

and then you can call it like this:

Method3(new GenericDerivedClass1());
+5
source

One solution is to use a non-generic base class for your generics:

abstract class GenericBaseClass
{
}

public class GenericDerivedClass1<T> : GenericBaseClass where T : DerivedClass1
{
}

- intefaces, .

+1

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


All Articles