Attribute is a way to associate additional data to an attribute (and other constructs), while enums are the most commonly used constructs in programming. Enumerations are essentially some constant values. Compared with directly using these constant values, enumerations provide us with better readability. We know that the basic type of an enum can only be value types (byte, sbyte, short, ushort, int, uint, long or ulong). In general, enums can meet our needs, but sometimes we need to add more information to the enum. It is not enough to just use these value types. At this time, by applying features to the enum types, the enum can have more information.
Using DescriptionAttribute feature in enumeration
First introduce: using namespace, the following is an enumeration that applies the DescriptionAttribute feature:
enum Fruit
{
[Description("Apple")]
Apple,
[Description("Orange")]
Orange,
[Description("Watermelon")]
Watermelon
}
Here is an extension method to obtain Description features:
/// <summary>
/// Get the enumeration description feature value
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="enumerationValue">Enumeration value</param>
/// <returns> Description of enumeration values/returns>
public static string GetDescription<TEnum>(this TEnum enumerationValue)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
Type type = ();
if (!)
{
throw new ArgumentException("EnumerationValue must be an enumeration value", "enumerationValue");
}
//Use reflection to obtain member information of the enum
MemberInfo[] memberInfo = (());
if (memberInfo != null && > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && > 0)
{
//Return to the enumeration worthy description information
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If there is no value describing the attribute, return the enum value string form
return ();
}
Finally, we can use this extension method to obtain the enumeration's worthy description information:
public static void Main(string[] args)
{
//description = "Orange"
string description = ();
}