. Net: Creation and viewing of custom attributes (named Attributes)

Source: Internet
Author: User



Sometimes we see something like this on a class or method:

          [Obsolete ("Please Update Method")]      

At first , he also gave it a name-small label, for example, usually said: "Your data contract is not labeled Ah!" ~ hehe ~ Later with the code found a lot more do not know the custom label. So, how are these tags defined and used?


define attribute


as follows, a attribute is defined that records class changes, does not allow inheritance, and allows multiple uses.

[AttributeUsage (AttributeTargets.Class, inherited = False, AllowMultiple = true)]//Public   Class Recordattribute: Attribute    {       private string recordtype;//record type: Update/create       private string author;//author       private DateTime date ;//Create/Update date       private string memo;//note       //constructor, the parameters of the constructor are also referred to as "positional parameters" in the attribute. Public       Recordattribute (string recordtype, string author, string date) {           this.recordtype = RecordType;           This.author = author;           This.date = convert.todatetime (date);       }       For positional parameters, typically only get accessor public       string RecordType {get {return recordtype;}}       public string Author {get {return Author;}}       Public DateTime Date {get {return Date;}}       Constructs an attribute, also called the "named parameter" public       string Memo {           get {return Memo;}           in the attribute set {memo = value;}       }    }



When used on a class:



    [Record ("Create", "LHC", "April 25, 2015 15:38:24", memo= "Here is the note information")]    [Record ("Modify", "LHC", "April 25, 2015 15:38:24", Memo = "Here is the note information")]      Public sealed class Democlass:baseclass, Idemointerface, IdemoInterface2 {        private string name;        private string City;        Public  readonly string title;        Public Const string Text = "const field";        public event Demodelegate MyEvent;        public string Name {            private get {return Name;}            set {name = value;}                }        Public DemoClass () {            title = "Readonly field";                        }        public class NestedClass {} public        void Saygreeting (string name)        {            Console.WriteLine ("Morning:" +name) ;        }            }


whether it is a constructor parameter or a property, it is all written into the parentheses of the constructor, and for the parameters of the constructor, the order and type of the constructor arguments must be taken, so called positional arguments; for attributes, the attribute = values, they are separated by commas, called named parameters.


It feels like the initialization information for a class is condensed to a single line ... The compression rate is quite high ah ~




Viewing custom attributes with Reflection


After using attributes, we can read the information inside. The basic idea is to get the same kind of metadata, first use the type, and then, hey, you know ~ to have everything ....



#region View custom attributes using reflection                Type t = typeof (Test.democlass);                Console.WriteLine ("The Recordattributes attribute applied to {0} is listed below:" + t);                Get all Reocordattributes properties                object[] records = T.getcustomattributes (typeof (Test.recordattribute), false);// Gets all Recordattribute label                foreach (Test.recordattribute item in records)                {                    Console.WriteLine ("{0}", item. ToString ());                    Console.WriteLine ("Type: {0}", item.) RecordType);                    Console.WriteLine ("{0}", item. Author);                    Console.WriteLine ("Date: {0}", item.) Date.tostring ());                    if (!string. IsNullOrEmpty (item. Memo)                    {                        Console.WriteLine ("Note: {0}", item.) Memo);                    }                }                            #endregion










. Net: Creation and viewing of custom attributes (named Attributes)

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.