我正在尝试创建一个系统,通过我将基类提升为派生类并使用它,但是如果你看到下面的错误,它似乎试图将'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是否会以不同的方式处理它......