How to enumerate an enum?
public static class EnumExtensions
{
///
/// Gets all items for an enum value.
///
///
/// The value. ///
public static IEnumerable
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
///
/// Gets all items for an enum type.
///
///
/// The value. ///
public static IEnumerable
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
///
/// Gets all combined items from an enum value.
///
///
/// The value. ///
///
/// Displays ValueA and ValueB.
///
/// EnumExample dummy = EnumExample.Combi;
/// foreach (var item in dummy.GetAllSelectedItems
/// {
/// Console.WriteLine(item);
/// }
///
///
public static IEnumerable
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
foreach (object item in Enum.GetValues(typeof(T)))
{
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
if (itemAsInt == (valueAsInt & itemAsInt))
{
yield return (T)item;
}
}
}
///
/// Determines whether the enum value contains a specific value.
///
/// The value. /// The request. ///
///
///
///
///
/// EnumExample dummy = EnumExample.Combi;
/// if (dummy.Contains
/// {
/// Console.WriteLine("dummy contains EnumExample.ValueA");
/// }
///
///
public static bool Contains
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
if (requestAsInt == (valueAsInt & requestAsInt))
{
return true;
}
return false;
}
}
The enum itself must be decorated with the FlagsAttribute
[Flags]
public enum EnumExample
{
ValueA = 1,
ValueB = 2,
ValueC = 4,
ValueD = 8,
Combi = ValueA | ValueB
}
http://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum
How to enumerate an enum?
Gönderen
pantepember
15 Haziran 2011 Çarşamba
Etiketler: enum