Enum – snippetów część pierwsza
Posted in Bez kategorii on Marzec 27th, 2011 by admin – Be the first to commentPrzy pracy z typami wyliczeniowymi często wykorzystuje się podobne fragmenty kodu, schematy (by nie rzec – wzorce projektowe), zatem postanowiłem je pozbierać – dla pamięci i na potrzeby przyszłych projektów.
1. Pętla oparta na wartościach typu wyliczeniowego:
enum TestEnumType { EnumValue1, EnumValue2, EnumValue3 };
static void Main(string[] args)
{
foreach (TestEnumType value in Enum.GetValues(typeof(TestEnumType)))
{
Console.Out.WriteLine(value);
}
Console.ReadLine();
}
2. Wartość liczbowa
enum TestEnumType { EnumValue1, EnumValue2, EnumValue3 };
static void Main(string[] args)
{
foreach (TestEnumType value in Enum.GetValues(typeof(TestEnumType)))
{
Console.Out.WriteLine((int)value);
}
Console.ReadLine();
}
3. Opisy wartości
Najpierw musimy sobie stworzyć klasę, która będzie zawierać extension methods. Zaczniemy od metody, która dla wartości enum zwróci wartość jej atrybutu Description (lub pusty string gdy ta wartość takiego atrybutu nie będzie miała zdefiniowanego):
public static class EnumExtensions
{
public static string ToDescriptionString<TEnum>(this TEnum val)
{
bool isEnum = val.GetType().IsEnum;
if (!isEnum)
throw new Exception("Parametr musi być enumeracją.");
DescriptionAttribute[] attributes;
attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
I wykorzystanie:
enum TestEnumType
{
[Description("Wartość początkowa")]
EnumValue1,
[Description("Wartość domyślna")]
EnumValue2,
[Description("Wartość dodatkowa")]
EnumValue3
};
static void Main(string[] args)
{
foreach (TestEnumType value in Enum.GetValues(typeof(TestEnumType)))
{
Console.Out.WriteLine(string.Format("{0}: {1}", value, value.ToDescriptionString()));
}
Console.ReadLine();
}
4. IsOneOf
Inną bardzo przydatną, nie tylko przy operacjach na typach wyliczeniowych, metodą jest:
public static bool IsOneOf(this T item, params T[] values)
{
return values.Contains(item);
}
I zastosowanie:
foreach (TestEnumType value in Enum.GetValues(typeof(TestEnumType)))
{
if (value.IsOneOf(TestEnumType.EnumValue1, TestEnumType.EnumValue2))
Console.Out.WriteLine(string.Format("{0} - Jest!", value));
}