简体   繁体   English

无法将派生类转换为基类

[英]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 . 我无法将派生类StopsVisited转换为其基类Stops The base class Stops is a collection of Stop. Stops基类是Stop的集合。 The derived class StopsVisited is a collection of StopVisited. 派生类StopsVisited是StopVisited的集合。

The element StopVisited derives from Stop (definitions not shown). StopVisited元素派生自Stop(未显示定义)。

I have a non-generics workaround where I simplly derive StopsVisited from Stops, but the generics afford me more felixibility. 我有一个非泛型解决方法,可以从Stops简化派生StopsVisited,但是泛型为我提供了更多的便利。 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' 错误1无法将类型'StopsHeirarchy.StopsVisited'隐式转换为'StopsHeirarchy.Stops'

Any help is appreciated. 任何帮助表示赞赏。

StopsVisited is not a subtype of Stops<Stop> ; StopsVisited不是Stops<Stop>的子类型; it's a subtype of Stops<StopVisited> , which is an entirely different thing. 它是Stops<StopVisited>的子类型,这是完全不同的事情。 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; 我同意duffymo的观点,子类型化是解决问题的错误方法,但是您要询问的特定功能在C#4中称为“协方差”或“输出安全”。 you can read about it here . 你可以在这里阅读。

Personally, I wouldn't use inheritance to say that a Stop has been visited. 就个人而言,我不会使用继承来表示已访问Stop。 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. 除非您可以说访问的Stop的行为有所不同,否则我建议不要在此设计中继承。

C# 4.0 solves this problem by modifying the CLR to support it. C#4.0通过修改CLR以支持它来解决此问题。

In the meantime, have an IStops interface (non-generic) and convert to it. 同时,拥有一个IStops接口(非通用)并转换成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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