The c enumeration value increase feature illustrates the of recommendation
- 2021-12-13 16:44:55
- OfStack
Adds a string description to each value of an enumeration type through attributes for printing or display.
Custom print characteristics
[AttributeUsage(AttributeTargets.Field)]
public class EnumDisplayAttribute : Attribute
{
public EnumDisplayAttribute(string displayStr)
{
Display = displayStr;
}
public string Display
{
get;
private set;
}
}
The print attribute definition is simple and contains only one string attribute.
Define 1 enumeration
public enum TestEnum
{
[EnumDisplay("1")]
one,
[EnumDisplay("2")]
two,
three
}
Enumeration types one and two both add one printing feature.
Adding enumeration expansion method to obtain printing characteristic value
public static class TestEnumExtentions
{
public static string Display(this TestEnum t)
{
var fieldName = Enum.GetName(typeof(TestEnum), t);
var attributes = typeof(TestEnum).GetField(fieldName).GetCustomAttributes(false);
var enumDisplayAttribute = attributes.FirstOrDefault(p => p.GetType().Equals(typeof(EnumDisplayAttribute))) as EnumDisplayAttribute;
return enumDisplayAttribute == null ? fieldName : enumDisplayAttribute.Display;
}
}
Gets the enumeration filed string corresponding to the enumeration value
var fieldName = Enum.GetName(typeof(TestEnum), t);
Get all custom feature sets corresponding to filed
var attributes = typeof(TestEnum).GetField(fieldName).GetCustomAttributes(false);
Get EnumDisplayAttribute features
var enumDisplayAttribute = attributes.FirstOrDefault(p => p.GetType().Equals(typeof(EnumDisplayAttribute))) as EnumDisplayAttribute
;
Returns its Display value if there is an EnumDisplayAttribute attribute, otherwise returns an filed string
return enumDisplayAttribute == null ? fieldName : enumDisplayAttribute.Display;
Use sample
class Program
{
static void Main(string[] args)
{
TestEnum e = TestEnum.one;
Console.WriteLine(e.Display());
TestEnum e1 = TestEnum.three;
Console.WriteLine(e1.Display());
Console.ReadKey();
}
}
Output:
1
three
Extended description
This method can not only add descriptive attributes to enumerated types, but also add custom attributes to attributes and methods of custom types. .
When using reflection to make
GetField(string name) GetMethod(string name) GetProperty(string name)
Equivalent requires a string
You can use nameof when getting a custom type property or method name string
public class T
{
public void Get()
{ }
public int Num { get; set; }
}
T tt = new T();
Console.WriteLine(nameof(tt.Num));
Console.WriteLine(nameof(tt.Get));