यह करने के लिए परंपरागत तरीके से उपयोग करने के लिए है Flagsएक पर विशेषता enum:
[Flags]
public enum Names
{
None = 0,
Susan = 1,
Bob = 2,
Karen = 4
}
फिर आप एक विशेष नाम के लिए जाँच करेंगे:
Names names = Names.Susan | Names.Bob;
// evaluates to true
bool susanIsIncluded = (names & Names.Susan) != Names.None;
// evaluates to false
bool karenIsIncluded = (names & Names.Karen) != Names.None;
लॉजिकल बिटवाइज़ कॉम्बिनेशन को याद रखना कठिन हो सकता है, इसलिए मैं अपने आप को एक FlagsHelperकक्षा * के साथ जीवन को आसान बनाता हूं :
// The casts to object in the below code are an unfortunate necessity due to
// C#'s restriction against a where T : Enum constraint. (There are ways around
// this, but they're outside the scope of this simple illustration.)
public static class FlagsHelper
{
public static bool IsSet<T>(T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
return (flagsValue & flagValue) != 0;
}
public static void Set<T>(ref T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue | flagValue);
}
public static void Unset<T>(ref T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue & (~flagValue));
}
}
यह मुझे उपरोक्त कोड को फिर से लिखने की अनुमति देगा:
Names names = Names.Susan | Names.Bob;
bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);
bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);
नोट मैं Karenऐसा करके सेट में भी शामिल हो सकता हूं :
FlagsHelper.Set(ref names, Names.Karen);
और मैं Susanएक समान तरीके से निकाल सकता था :
FlagsHelper.Unset(ref names, Names.Susan);
* जैसा कि पोरगेस ने बताया, IsSetऊपर दी गई विधि का एक समकक्ष .NET 4.0 में पहले से मौजूद है Enum.HasFlag। Setऔर Unsetतरीकों, हालांकि समकक्ष है प्रतीत नहीं होते हैं; इसलिए मैं अभी भी कहूंगा कि इस वर्ग में कुछ योग्यता है।
नोट: एनम का उपयोग करना इस समस्या से निपटने का पारंपरिक तरीका है। आप इसके बजाय इनट्स का उपयोग करने के लिए उपरोक्त सभी कोड का पूरी तरह से अनुवाद कर सकते हैं और यह बस के रूप में भी काम करेगा।