简体   繁体   中英

Cannot Convert Derived Class to Base Class

I am working on a transportation problem and cannot leap this hurdle. I am unable to convert the derived class StopsVisited to its base class Stops . The base class Stops is a collection of Stop. The derived class StopsVisited is a collection of StopVisited.

The element StopVisited derives from Stop (definitions not shown).

I have a non-generics workaround where I simplly derive StopsVisited from Stops, but the generics afford me more felixibility. I've tried to reduce it to its simplest form.

Base

public abstract class Stops<T> where T : Stop 
{

}

Derived

public class StopsVisited : Stops<StopVisited>
{

}

The problem:

Stops<Stop> stops = new StopsVisited();

Gives me a

Error 1 Cannot implicitly convert type 'StopsHeirarchy.StopsVisited' to 'StopsHeirarchy.Stops'

Any help is appreciated.

StopsVisited is not a subtype of Stops<Stop> ; it's a subtype of Stops<StopVisited> , which is an entirely different thing. I agree with duffymo that subtyping is the wrong approach to your problem, but the specific feature you're asking about is called "covariance" or "output-safe" in C# 4; you can read about it here .

Personally, I wouldn't use inheritance to say that a Stop has been visited. I'd have a boolean data member to say that a Stop had been visited. It seems like a binary attribute - you've either been visited or you haven't.

Inheritance ought to be about different behaviors. Unless you can say that a visited Stop somehow behaves differently, I would advise against inheritance in this design.

C# 4.0 solves this problem by modifying the CLR to support it.

In the meantime, have an IStops interface (non-generic) and convert to it.

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