简体   繁体   中英

Generic base class where T is also a generic base class

I have a generic base class something like:

public abstract class SomeThingBase<T> where T : class

I'd like to have another base class something like this:

public abstract class MangerBase<T> where T : SomeThingBase<T>

How do you accomplish this in C#? When trying to use ManagerBase like this it doesn't seem to work.

class TestManager : ManagerBase<TestSomething>

In order to do this you have to pass your generic declarations in all the way from the top. This can get very messy, so avoid doing it.

public abstract class SomeThingBase<T> where T : class{ }
public abstract class ManagerBase<T, U> 
    where T : SomeThingBase<U>
    where U : class
{ }

It's definitely possible to define, but impossible to actually implement. Assuming you have the below definition:

    public abstract class SomeThingBase<T> where T : class { }
    public abstract class MangerBase<T> where T : SomeThingBase<T> { }

However, defining a class that implements ManagerBase<T> and SomethingBase<T> is impossible since multiple inheritance is not supported and T cannot meet both constraints without multiple inheritance the generic type.

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