Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 继承通用can';t向上投射_C#_Generics_Inheritance - Fatal编程技术网

C# 继承通用can';t向上投射

C# 继承通用can';t向上投射,c#,generics,inheritance,C#,Generics,Inheritance,我在继承自定义泛型时遇到问题。编译器(Visual Studio for Mac)抱怨继承泛型不能隐式转换为另一个继承类型。我的代码细分如下: 我有一个名为IAnsweredCommon的接口和另一个从中继承的名为IAnsweredAndroid的接口 public interface IAnsweredCommon 及 我还有另外两个类使用这些接口 public abstract class ConstructorCommon<AnsweredType> where Answer

我在继承自定义泛型时遇到问题。编译器(Visual Studio for Mac)抱怨继承泛型不能隐式转换为另一个继承类型。我的代码细分如下:

我有一个名为IAnsweredCommon的接口和另一个从中继承的名为IAnsweredAndroid的接口

public interface IAnsweredCommon

我还有另外两个类使用这些接口

public abstract class ConstructorCommon<AnsweredType> where AnsweredType : IAnsweredCommon
公共抽象类构造函数common,其中AnsweredType:IAnsweredCommon

公共类构造函数android:ConstructorCommon
这很有效。公共构造函数有一个AnsweredType的成员变量,允许它将其视为IAnsweredCommon并针对其运行操作系统无关代码,同时允许Android构造函数访问相同的成员变量,并将其视为IAnsweredAndroid,允许Android构造函数针对其运行Android特定代码。Android构造函数可以处理特定于Android的事情,同时将操作系统无关的代码传递给公共构造函数。这是我想要的,因为它允许我将其扩展到iOS。

现在的问题是,我在构造函数的顶部有另一层。构造函数基本上实现了builder设计模式,因此它有很多方法可以调用,以构造一个响应对象。我有一些控制器类,它们调用预先确定的构造函数方法来创建预先确定的对象

public abstract class DirectorCommon<AnsweredConstructorType>
    where AnsweredConstructorType : ConstructorCommon<IAnsweredCommon>
公共抽象类DirectorCommon
其中AnsweredConstructorType:ConstructorCommon

公共类DirectorAndroid:DirectorCommon
编译器抱怨无法将ConstructorAndroid隐式转换为ConstructorCommon。出于测试目的,我对ConstructorAndroid进行了扩展,并将其临时更改为:

public class DirectorAndroid : DirectorCommon<ConstructorCommon<IAnsweredAndroid>>
公共类DirectorAndroid:DirectorCommon
现在,如果我将IAnsweredAndroid接口更改为IAnsweredCommon,错误就会消失(因为它与约束完全匹配)。但是如果我把它改成IAnsweredAndroid,我会得到错误。我很困惑,因为IAnsweredAndroid是IAnsweredCommon(继承),因此编译器应该能够将IAnsweredAndroid向上转换为IAnsweredCommon。毕竟,它是在构造函数类中这样做的。


注意:我已经清理了代码以使其更易于阅读(删除了名称空间、不相关的代码等等),因此代码可能无法“运行”,但无论如何,请指出任何错误,我确信这是我遗漏的一件小事,您永远不知道错误是因为清理还是实际错误。

这是不可能的,
不可分配给
,如果A从B派生,反之亦然

如果ConstructorCommon是接口IConstructorCommon,并且定义为:

interface IConstructorCommon<out AnsweredType> where AnsweredType : IAnsweredCommon
接口IConstructorCommon,其中应答类型:IAnsweredCommon
“out”使其协变

用接口替换抽象基类型可能比较合适`

您的错误与约束无关,您找到匹配项的方式与类型匹配无关。您可以将
ConstructorComman
分配给
ConstructorCommon
,但不能分配给
ConstructorCommon
,无论是否存在约束。仅当要调用仅受约束类型具有的特殊方法时才需要约束

  public class DirectorAndroid : DirectorCommon<ConstructorAndroid>
public class DirectorAndroid : DirectorCommon<ConstructorCommon<IAnsweredAndroid>>
interface IConstructorCommon<out AnsweredType> where AnsweredType : IAnsweredCommon