我需要知道一种同时处理一个对象的有效方法,以便在不使用开关的情况下控制这 3 个类中的一个。 (随时了解对象类型)
注意:AddVertex 方法没有被重载,所以它对父类是通用的。
switch (User.Action)
{
case Actions.NewVertex:
switch (GraphsType)
{
case GraphsType.None:
Graph.AddVertex(p); /*This is the parent class*/
break;
case GraphsType.UndirectedGraph:
UndirectedGraph.AddVertex(p); /*This is a derived class*/
break;
case GraphsType.DirectedGraph:
DirectedGraph.AddVertex(p); /*This is a derived class,*/
break;
}
}
请您参考如下方法:
如我所见,您只想编写用户命令处理程序。
没有大问题。只需制作一本字典(var GraphsType -> Graph)。
var dictionary = new Dictionary<GraphsType, Graph>() {
{ GraphsType.None, GraphObject },
{ GraphsType.UndirectedGraph, UndirectedGraphObject },
{ GraphsType.DirectedGraph, DirectedGraphObject },
};
并使用它:
dictionary[GraphType].AddVertex(v);
如果你的 Graph、UndirectedGraph、DirectedGraph 是静态类,你必须在字典中保存它的类型 (typeof(Graph)) 然后在类型上使用反射找到方法并调用它 (字典[GraphType].GetMethod(..).Invoke(...))
