Attribute is a method of associating additional data to an attribute (and other constructor), while enumeration is the most commonly used structure in programming, enumeration is essentially a constant value. Compared to using these values directly, enumeration provides us with better readability. We know that the basic type of enumeration can only be value type (Byte,Sbyte,Short,Ushort,Int,Uint,LongOrUlong), in general, enumeration can meet our needs, but sometimes we need to add more information for enumeration, just using these value types is not enough, in this case, you can apply the features of the enumeration type to bring more information to the enumeration.
Use descriptionattribute in Enumeration
First introduce:Using system. componentmodelNamespace. The following is an enumeration application.DescriptionattributeFeatures:
1 Enum Fruit 2 { 3 [Description ( " Apple " )] 4 Apple, 5 [Description ( " Orange " )] 6 Orange, 7 [Description ( " Watermelon " )] 8 Watermelon 9 }
The following is an extension method for obtaining the description feature:
1 /// <Summary> 2 /// Obtains enumeration description feature values. 3 /// </Summary> 4 /// <Typeparam name = "tenum"> </typeparam> 5 /// <Param name = "enumerationvalue"> Enumerated Value </Param> 6 /// <Returns> Description of enumerated values/returns> 7 Public Static String Getdescription <tenum> ( This Tenum enumerationvalue) 8 Where Tenum: Struct , Icomparable, iformattable, iconvertible 9 { 10 Type type = Enumerationvalue. GetType (); 11 If (! Type. isenum) 12 { 13 Throw New Argumentexception ( " Enumerationvalue must be an enumerated value. " , " Enumerationvalue " ); 14 } 15 16 // Use reflection to obtain the member information of this enumeration. 17 Memberinfo [] memberinfo = Type. getmember (enumerationvalue. tostring ()); 18 If (Memberinfo! = Null & Amp; memberinfo. Length & gt; 0 ) 19 { 20 Object [] Attrs = memberinfo [ 0 ]. Getcustomattributes ( Typeof (Descriptionattribute ), False ); 21 22 If (Attrs! = Null & Amp; attrs. Length & gt; 0 ) 23 { 24 // Return enumeration value description 25 Return (Descriptionattribute) attrs [ 0 ]). Description; 26 } 27 } 28 // If no feature value is described, return the string format of this enumeration. 29 Return Enumerationvalue. tostring (); 30 }
Finally, we can use this extension method to obtain the descriptive information of this enumeration:
1 Public static void main ( string [] ARGs) 2 { 3 /// description =" orange " 4 string description = fruit. orange. getdescription (); 5 }