I. Overview
Attribute plainly is a class, inside the general contains some additional information, or some special processing logic, in order to tell the compiler to apply the features of the East is a wonderful, need special treatment!
second, the use of matters needing attention
2.1. Attribute is a class that must inherit from System.Attribute
2.2 Attribute naming specification
Attribute naming generally ends with attribute, but in the specific use, you can omit the attribute suffix. Join defines a helperattribute, which can be used to write [Helper].
Restrictions on the use of 2.3 attribute
The attribute class, when defined, can specify the scope of application of this attribute, AttributeTargets enumeration lists the ranges that can be specified, which can be class, field, and so on, and Allowmutiple is true or false. This means that the feature is reused somewhere (for example, multiple times on a class); inherited is true or false, meaning whether the attribute will be inherited by subclasses of the class to which the attribute is applied.
2.4 Parameter Assignment in attribute
Positional parameters (parameters of the attribute constructor): required and consistent in order!
Named parameters (other fields or attributes in attribute): can be omitted when used!
Iii. Customizing a attribute and reading its values
Give me a chestnut:
[AttributeUsage (AttributeTargets.Class, Allowmutiple=true, Inherited=false)]
Public classBookattribute:attribute
{
Public stringMSG {Get;Set; }
Public DoubleVersion =1.0;
PublicMyfirstattribute (stringmsg)
{
MSG=msg;
}
}
Get attribute related information by reflection:
namespaceTestattribute {
using attribute classes multiple times
[Book ("people posts and telecommunications")] [Book ("Beijing")]classBookInfo { Public stringBookInfo ="Book Information"; //constructor Function PublicBookInfo () {} }}
Static voidMain (string[] args) {BookInfo BookInfo=NewBookInfo (); MemberInfo TypeInfo=typeof(BookInfo); Object[] bookarr= TypeInfo. GetCustomAttributes (typeof(Bookattribute),false); if(Bookarr. GetLength (0) !=0) {Bookattribute bookattribute1= (Bookattribute) bookarr[0]; Bookattribute Bookattribute2 = (bookattribute) bookarr[1];Console.WriteLine (Bookinfo.bookinfo); Console.WriteLine ("Publishing houseare:"+ bookattribute1. msg+"The city is:"+Bookattribute2. MSG); Console.readkey (); } }
Four, learn to use some. NET built-in features
Give me a chestnut:
System.ObsoleteAttribute: Tells the compiler that a method is obsolete, and then a warning message is given when the compiler discovers that there is a place in the program that uses this obsolete-tagged method.
Class TestClass
{
Add Obsolete attribute
[Obsolete ("Use the new Sendmsg (Message msg) overloaded method")]
void ShowMsg ()
{
Console.WriteLine ("This is the old Sendmsg () method");
}
}
void button1_click (object sender, EventArgs e)
{
Testclass.showmsg ();
}
Now run this code and we'll see that the compiler gives a warning!
The application of attribute on enumeration
enum gender{ [Description ("male")] man , [Description ("female")] Woman};
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Reflection; namespaceMyTools {/// <summary> ///Enumerating Helper Classes/// </summary> Public Static classEnumhelper {/// <summary> ///gets the attribute of the enumeration item/// </summary> /// <typeparam name= "T" >Custom Attribute</typeparam> /// <param name= "source" >Enumeration</param> /// <returns>returns an enumeration, otherwise returns null</returns> Public StaticT getcustomattribute<t> (Enum source)whereT:attribute {Type sourcetype=source. GetType (); stringSourceName =Enum.getname (sourcetype, source); FieldInfo Field=Sourcetype.getfield (sourceName); Object[] attributes = field. GetCustomAttributes (typeof(T),false); foreach(ObjectAttributeinchattributes) { if(Attribute isT)return(T) attribute; } return NULL; } /// <summary> ///Get DescriptionAttribute Description/// </summary> /// <param name= "source" >Enumeration</param> /// <returns>has a description tag, returns a token description, otherwise returns null</returns> Public Static stringGetDescription ( ThisEnum Source) { varattr = getcustomattribute<system.componentmodel.descriptionattribute>(source); if(attr = =NULL) return NULL; returnattr. Description; } Public StaticENUMT getvaluebydescription<enumt> (stringdescription) { varType =typeof(ENUMT); if(!type. Isenum)Throw NewArgumentException ("This method was destinated for the enum types only."); foreach(varEnumnameinchenum.getnames (type)) { varEnumvalue =enum.parse (type, enumname); if(Description = =(Enum) enumvalue). GetDescription ())return(enumtype) enumvalue; } Throw NewArgumentException ("there is no. value with the this description among specified enum type values."); } } }
How to use:
Gender.Man.GetDescription ()
Five, pay attention to the MVC characteristics of the ingenious application, rewrite!
Characteristics of C # secret weapons