CS0311 在 class headers 中扩展泛型类型时出错

CS0311 Error when extending generic types in class headers

CS0311:类型 'type1' 不能用作泛型类型或方法“”中的类型参数 'T'。没有从 'type1' 到 'type2'.

的隐式引用转换

我有这两个 class 开头:

public abstract class Node<N> where N : Node<N> { ... }
public class Pathfinder<N> where N : Node<N> { ... }

然后,我有一个名为 Node2D 的 Node 实现,它采用不同的通用类型,它必须扩展另一个名为 World 的 class。

public abstract class World<W> where W : World<W> { ... }
public class Node2D<W> : Node<Node2D<W>> where W : World<W> { ... }

我可以毫无问题地创建类型为 Pathfinder> 的 object(见下文)。但是,当我尝试使用扩展 Node2D 的类型创建 Pathfinder 时,VSC 给我一个 CS0311 错误。当我进行以下特定 classes:

时会发生这种情况
public class TestWorld : World<TestWorld> { ... }
public class TestNode : Node2D<TestWorld> { ... }

// inside some function
Pathfinder<TestNode> pathfinder = new Pathfinder<TestNode>(); // gives CS0311 error where type1 is TestNode, and type2 is Node<TestNode>

当我制作一个 class 来包含 Pathfinder

的具体实现时也会发生这种情况
public class Pathfinder2D<X, W> where X : Node2D<W> where W : World<W> {

    private Pathfinder<X> _pathfinder; // gives CS0311 error where type1 is X, type2 is Node<X>

}

为什么最初的 Pathfinder 适用于任何 W 类型的 Node2D< W >,但不适用于 Node2D< W > 的特定实现?如果根本不允许泛型类型的扩展,我认为 Node2D 也行不通,只能使用原始的 Node 作为 Pathfinder 的类型。既然这行得通,我就认为只要我有一个带有特定 W 的 Node2D 实现,它就应该与 Pathfinder 一样工作。如果 Pathfinder< Node2D< TestWorld >> 工作,为什么 Pathfinder< TestNode > where TestNode is Node2D< TestWorld >?

CS0311 声明在此声明中

Pathfinder<TestNode> p;

TestNode 必须可转换为 Node<TestNode>。这就是 Pathfinder<T> 的通用参数的约束状态:

public class Pathfinder<N> where N : Node<N>

但是TestNode是从Node2D<Testworld>派生出来的。并且根据Node2D<T>

的声明
public class Node2D<W> : Node<Node2D<W>>

我们知道TestNode实际上是一个Node<Node2D<Testworld>>。那是不是一个Node<TestNode>.

所以你的通用声明和约束是矛盾的。

这似乎是一个设计缺陷,如何解决这个问题取决于您要实现的目标。