The following is a way to return a string using a tag to an enumeration
Each of the following defines an attribute class, and an enumeration helper class
[CSharp]View Plaincopyprint?
- [AttributeUsage (attributetargets.field,allowmultiple = false)]
- Public sealed class Enumdescriptionattribute:attribute
- {
- private string description;
- public string Description { get { return Description;}}
- Public Enumdescriptionattribute (string description)
- : base ()
- {
- this.description = description;
- }
- }
[CSharp]View Plaincopyprint?
- Public static class Enumhelper
- {
- public static string getdescription (Enum value)
- {
- if (value = = null)
- {
- throw New ArgumentException ("value");
- }
- string description = value. ToString ();
- var fieldInfo = value. GetType (). GetField (description);
- var attributes =
- (enumdescriptionattribute[]) fieldinfo.getcustomattributes (typeof (Enumdescriptionattribute), false);
- if (attributes ! = null && attributes. Length > 0)
- {
- Description = Attributes[0]. Description;
- }
- return description;
- }
- }
Examples of Use:
[CSharp]View Plaincopyprint?
- Enum Week
- {
- [Enumdescription ("Monday")]
- Monday,
- [Enumdescription ("Tuesday")]
- Tuesday
- }
- The following prints the result: Monday
- Console.WriteLine (Enuhelper.getdescription (Week.monday))
Go-c# Let the enumeration return a string