0

我正在尝试创建一个系统,通过将基类提升为派生类并照此使用它,但是如果您看到下面的错误,它似乎正在尝试将“NodeType”转换为派生类型,即使 NodeType 是不是真正的类型。

这不起作用:

class Node {}
class Navpoint : Node {}
class Jumppoint : Node {}

class Actor {
  public static void on<NodeType>(Actor actor, Node node) where NodeType : Node {
     actor.Navigate(node as NodeType);  // error: (CS1502) cannot convert NodeType to Navpoint
  }

  private static IDictionary<System.Type, Navigation> navigations = 
    new Dictionary<System.Type, Navigation>() {
     {typeof(Navpoint), on<Navpoint>},
     {typeof(Jumppoint), on<Jumppoint>},
  };

  public void Navigate(Node node) {
   navigations[node.GetType()](this, node);
  }
 public void Navigate(Navpoint navpoint) {
     // do something with navpoint
  }
  public void Navigate(Jumppoint jumppoint) {
     // do something with jumppoint
 }
}

然而,这确实有效:

class Node {}
class Navpoint : Node {}
class Jumppoint : Node {}

class Actor {
  public static void onNavpoint(Actor actor, Node node) {
     actor.Navigate(node as Navpoint);  // works fine
  }
  public static void onJumppoint(Actor actor, Node node) {
     actor.Navigate(node as Jumppoint);  // works fine
  }

  private static IDictionary<System.Type, Navigation> navigations = 
    new Dictionary<System.Type, Navigation>() {
     {typeof(Navpoint), onNavpoint},
     {typeof(Jumppoint), onJumppoint},
 };

  public void Navigate(Node node) {
    navigations[node.GetType()](this, node);
  }
  public void Navigate(Navpoint navpoint) {
     // do something with navpoint
 }
  public void Navigate(Jumppoint jumppoint) {
     // do something with jumppoint
 }
}

输入大约 20 行几乎重复的代码并没有什么大不了的,但我的问题是为什么?

我也在使用 Unity 和 MonoDevelop,我不知道 .NET 是否会以不同的方式处理这个问题。

4

0 回答 0