1

我需要知道一种有效的方法来处理一个对象,以便在没有开关的情况下控制这 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;
                    }
             }
4

1 回答 1

4

如我所见,您只想编写用户命令处理程序。

没有什么大问题。只需制作一个字典(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))保存在字典中,然后在类型上使用反射查找方法并调用它(dictionary[GraphType].GetMethod(..).Invoke(...)

于 2013-07-08T22:14:50.980 回答