An attribute is a class that needs to inherit or indirectly inherit System.Attribute.
1. Common features
AttributeUsage: defines the attribute definition to the target element.
Flags: The enumeration value is used as a bit marker, not as a numeric value.
[Flags] publicenum Animal { 0x0001, 0x0002, 0x0004, 0x0008 } = animal.dog| Animal.cat; WriteLine (animal. ToString ()); // Animal Use the flags attribute, output dog,cat, and do not use the flags attribute, output 3
DllImport: call unmanaged code.
Public classDllimportdemo {[DllImport ("User32.dll")] Public Static extern intMessageBox (intHparent,stringMsgstringCaptioninttype); Public Static intMain () {returnMessageBox (0,"Using Attributes",". NET Attribute",0); } } //calledDllimportdemo.main ();
2. Try to write a feature yourself
[AttributeUsage (Attributetargets.property,//Apply to PropertiesAllowMultiple =false,//do not allow multiple applicationsinherited =false)]//do not inherit to a derived class Public classTrimAttribute:System.Attribute { PublicType type {Get;Set; } Publictrimattribute (Type type) {type=type; } } /// <summary> ///Trimattribute: Implement extension method Trim ()--Must be static class, static method, first parameter with this decoration/// </summary> Public Static classTrimattributeext { Public Static voidTrim ( This Objectobj) {Type Tobj=obj. GetType (); foreach(varPropinchTobj. GetProperties ()) {//GetCustomAttributes (typeof (Trimattribute), false), returns the attribute of the Trimattribute identity foreach(varattrinchProp. GetCustomAttributes (typeof(Trimattribute),false) {trimattribute tab=(Trimattribute) attr; if(Prop. GetValue (obj)! =NULL&& tab. Type = =typeof(string) {Prop. SetValue (obj, getpropvalue (obj, prop. Name). ToString (). Trim (),NULL); } } } } Private Static ObjectGetPropValue (ObjectObjstringpropname) { //invokes the specified member by using the specified binding constraint and matching the specified argument list returnObj. GetType (). InvokeMember (propname, BindingFlags.GetProperty,NULLObjNew Object[] { }); } }Attribute Class Code
Public classUser { Public intId {Get;Set; } [Trim (typeof(string))] Public stringUserName {Get;Set; } [Trim (typeof(string))] Public stringPassword {Get;Set; } } using StaticSystem.Console;//static classes can use the using staticnamespaceconsoletest{classProgram {Static voidMain (string[] args) { //Dllimportdemo.main ();User User=NewUser {Id =1, UserName ="Admin", Password ="1234" }; User. Trim ();//the line is commented out with a blank spaceWriteLine ("|"+ user. UserName +"|"); ReadKey (); } }}Using Code
C # Features