attribute can be used for information mapping, more flexible and decoupled than dictionary or Tuple,attribute, and can correspond to many types
The following is an information map of the field in an enum
1. Create field attribute
[AttributeUsage (Attributetargets.field)] public class Jobactionmetadatattribute:attribute {public jobactionuitype uitype {get; private set;} public string Label {get; private set;} Public Jobactionmetadatattribute (Jobactionuitype uitype, string label) { uitype = Uitype; label = label; } }
2. Prepare a extension method
public static class Jobactionextenssion {public static jobactionmetadata GetMetaData (this jobaction jobaction ) {var attr = Attribute.GetCustomAttribute (Jobaction.gettype (). GetMember (Jobaction.tostring ()) [0], typeof (Jobactionmetadatattribute)); if (attr! = null) {var props = attr. GetType (). GetProperties (); Jobactionuitype Uitype; var uitypeobj = props. FirstOrDefault (p = P.propertytype = = typeof (Jobactionuitype)); if (uitypeobj = = null) {throw new Invaliddataexception (string. Format ("Failed to find Jobactionuitype property in Jobactionmetadataattribute")); } var uitypestr = Uitypeobj.getvalue (attr, NULL). ToString (); if (! Enum.tryparse (Uitypestr, True, out Uitype)) {throw new invalidenumargumentexception (str Ing. Format ("Enum parsing failed. StrinG: {0} ", uitypestr)); } var label = props. First (p = = P.name = = "Label"). GetValue (attr, NULL). ToString (); return new Jobactionmetadata (Jobaction, Uitype, Label, ""); } Throw new Invaliddataexception (string. Format ("Failed to find Jobactionmetadatattribute for Action: {0}", jobaction)); } }
3. Applying attributes on the field of an enum
Public enum jobaction { [Jobactionmetadatattribute (jobactionuitype.success, "Paypal Payment")] makepaypalsimplepayment = 0, [Jobactionmetadatattribute (Jobactionuitype.success, "pay by Free Pass")] Makefreepasspayment = 1, [Jobactionmetadatattribute (Jobactionuitype.success, "pay by company credits")] Makecompanycreditpayment = 2, }
4. Use
Job. Jobaction.getmetadata ();
Use attribute + extension method to complete information mapping of field in enum