After the swich....case condition branches more, it will seriously destroy the aesthetics of the program.
Like this one.
The code above is used to communicate between two processes of code, because the enumeration of communication is particularly many, so the branch of case is particularly much. Causes the code to be readable, and maintainability is severely degraded. After finding the data and refactoring, I think of a feasible scheme to replace switch...case in this case —————— use key-value pairs.
Declaring a key-value pair object
For the code logic of process communication, the following key-value pairs are constructed.
Dictionary<enummsg, action<message>> mmessagereceiver = new Dictionary<enummsg, Action<Message> > ();
The key for this key-value pair is a custom message enumeration, and Action<Message>
the value is the delegate. This corresponds to the handler function for the message enumeration and the message enumeration corresponding to one by one.
Registering messages when initializing
At initialization time, the enumeration is loaded with the corresponding action.
private void Subscribemessagereceiver () { mmessagereceiver.add (Enummsg.send_pano_param, Updatepano); Mmessagereceiver.add (Enummsg.cmd_pano_view, executepanoviewcommand); Mmessagereceiver.add (Enummsg.cmd_pano_length_measure, executelengthmeasure); Mmessagereceiver.add (Enummsg.cmd_pano_area_measure, executeareameasure); Mmessagereceiver.add (Enummsg.cmd_pano_quick_pick, Executeqickpickcommand);}
This completes the key-value construction of the object. You can then refactor the Swith...case code snippet.
modifying Switch...case Code Snippets
Switch....case Code before refactoring
protected override void Defwndproc (ref Message m) { switch (m.msg) {case (int) API. Wm_copydata): { switch ((int) m.wparam) {case ((int) procedure.openskyline): m = Openskylineview (m); break; Case ((int) procedure.measureare): m = Measure (m); break; Case ((int) procedure.measurelength): m = Measure (m); break; } } break; Default: Break ; } Base. Defwndproc (ref m); }
Code to find the corresponding processing method based on a key-value pair
protected override void Defwndproc (ref Message m) { base. Defwndproc (ref m); if (m.msg = = (int) API. Wm_copydata) { enumpanomsg penumpanomsg = (enumpanomsg) M.wparam; if (MMessageReceiver.Keys.Contains (penumpanomsg)) { mmessagereceiver[penumpanomsg] (m); } }
Based on key-value pairs of keys to find, when the need to add a new case branch, the original method needs to change the Switch....case branch, but the use of key-value pairs method, only need to write a new processing method, and in the key-value pairs to add a new pair of key values can be. The code is simple and beautiful, without a long list of annoying case.