This article is a mirror article of machine translation, please click here to jump to the original article.

View: 17153|Reply: 0

[Communication] C# enumeration value increase feature description

[Copy link]
Posted on 1/28/2019 10:48:27 AM | | |
Adds a string description to each value of an enum type through a feature for printing or display.

Customize the print characteristics

The print feature definition is simple and contains only one string attribute.

Define an enum

Enumeration types one and two both add a print feature.

Add the enum extension method to obtain the print characteristic value


  • Get the enum string corresponding to the filed value of the enum var fieldName = Enum.GetName(t_type, t);
  • Get all the custom attribute sets corresponding to filed var attributes = typeof(TestEnum). GetField(fieldName). GetCustomAttributes(false);
  • Get the EnumDisplayAttribute property var enumDisplayAttribute = attributes. FirstOrDefault(p => p.GetType(). Equals(typeof(EnumDisplayAttribute))) as EnumDisplayAttribute;
  • If the EnumDisplayAttribute property exists, returns its Display value, otherwise returns the filed string return enumDisplayAttribute == null ? fieldName : enumDisplayAttribute.Display;


Usage examples

Output:

One  
three
Extended Instructions

This method can not only add explanatory properties to the enum type, but also add custom characteristics to the custom type.
When using reflections, strings are required for GetField(string name), GetMethod(string name), GetProperty(string name), etc
You can use nameof when getting a custom type attribute or method name string







Previous:Monday, January 28 Xie You Morning Post
Next:The use of angle brackets in c#, such as List<int>
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com