C # Features

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.