How can we break through too many member variables ?, Member variables
In the process of software development, we often encounter more and more member variables of a class, which is messy. Is there an elegant solution? If most of these variables are BOOL type, you can use BitArray to manage these variables. For other types, you can create a data structure to include them.
BitArray: Manages a compact array of bit values, which are represented as Booleans, whereTrue indicates that the bit is on (1) and false indicates the bit is off (0 ).
public class BitArrayTest { private BitArray bitArray; public BitArrayTest() { int leng = Enum.GetValues(typeof(Flag)).Length; bitArray = new BitArray(leng); } public bool GetFlag(Flag flag) { lock(bitArray.SyncRoot) { return bitArray[(int)flag]; } } public void SetFlag(Flag flag, bool result) { lock(bitArray.SyncRoot) { bitArray[(int)flag] = result; } } public void ResetFlag() { lock (bitArray.SyncRoot) { bitArray.SetAll(false); } } public void SetFlagTrue(Flag flag) { SetFlag(flag, true); } public void SetFlagFalse(Flag flag) { SetFlag(flag, false); } }View Code
For example, if you have the member variables flagOne, flagTwo, and flagThree, you can use an enumeration class to map the variables:
public enum Flag { flagOne, flagTwo, flagThree, }View Code
Set and read variables:
BitArrayTest test = new BitArrayTest(); test.SetFlagTrue(Flag.flagOne); if (test.GetFlag(Flag.flagOne)) { }View Code
Is the code neat?