简体   繁体   中英

Descendant non-generic class into Base generic class

Usually I Use interfaces or base classes as paramter types when passing derived objects to a method. For example

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

But what about a Generic base class when the descendant class isn't generic ?

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

public class GenericDerivedClass1 : GenericBaseClass<DerivedClass1>
{}

I can write something like

Method3(GenericBaseClass<BaseClass> class);

but I can't pass to this method am object of type GenericDerivedClass1 .

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

You need to make your Method3 generic:

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

}

and then you can call it like this:

Method3(new GenericDerivedClass1());

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

abstract class GenericBaseClass
{
}

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

Another solution is to use intefaces as pointed out in this article.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM