swich....case If there are too many conditional branches, it will seriously damage the beauty of the program.
For example, this
The above code is used for communication between two processes. Since there are many enumerations for communication, there are many case branches. As a result, the readability and maintainability of the code are seriously reduced. After searching for information and reconstructing, I came up with a feasible alternative to switch...case in this situation——using key-value pairs.
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 of this key-value pair is a custom message enumeration, and the value is the delegate of Action<Message>
. In this way, the message enumeration and the processing functions corresponding to the message enumeration are in one-to-one correspondence.
During initialization, load the enumeration and 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 construction of the key-value pair object. Then you can refactor the swith...case code segment.
Switch....case code before reconstruction
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 key-value pairs
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); } } }
Search based on the key of the key-value pair. When a new case branch needs to be added, the original method requires changing the switch....case branch, but using the key-value pair method, only Just write a new processing method and add a new pair of key values to the key value pair. The code is concise and beautiful, without a long list of boring cases.
The above is the detailed content of C# example of how to use key-value pairs to replace the Switch...Case statement. For more information, please follow other related articles on the PHP Chinese website!