. NET Fundamentals (18) features

Source: Internet
Author: User

Characteristics
1 What is an attribute and how to customize an attribute
2. What elements can be used by attributes in net
3 There are several ways to know whether an element declares an attribute
Whether 41 elements can be repeated to declare the same feature

Characteristics
1 What is an attribute and how to customize an attribute

A feature is a special mechanism for declaring programming, which is a family of types that inherit from System.Attribute, and at compile time, the use of the attribute is written to the metadata, either in a common run or in the reflection of the program. Customizing an attribute essentially defines a type that inherits from System.Attribute.

Examples of custom attributes:

    /// <summary>    ///Custom Attributes/// </summary>[AttributeUsage (AttributeTargets.Class)] Public classMyattribute:attribute {PrivateString _classname;  PublicMyAttribute (String s) {_classname=s; }        //A read-only property         PublicString ClassName {Get            {                return_classname; }        }    }    /// <summary>    ///using custom Properties/// </summary>[MyAttribute ("Usemyattribute")]    classUsemyattribute {Static voidMain (string[] args) {Type T=typeof(Usemyattribute); object[] Attributes= T.getcustomattributes (false); MyAttribute att= (myattribute) attributes[0]; Console.WriteLine (Att.            ClassName);        Console.read (); }    }

Output:

Usemyattribute

Attributes are written to the metadata, so the use of attributes is basically based on the reflection mechanism.

There are a few points to note:

    • By convention, the names of the attributes end with attribute.
    • In C #, for ease of use, you can omit the attribute name suffix attribute, such as [MyAttribute ("Usemyattribute")], which can be written as [My ("Usemyattribute")].
    • The attribute itself can add additional attributes.


2. What elements can be used by attributes in net

Attributes can be applied on target elements such as assemblies, modules, structs, enumerations, construction methods, methods, properties, fields, events, interfaces, parameters, delegates, return parameters, and generic parameters. The AttributeUsage feature allows you to limit the use of custom attributes.

Example:

usingSystem;//apply on an assembly[Assembly:myattribute]//apply to the module[Module:myattribute]//Apply on Type[Type:myattribute]classAttributetargets<[typevar:myattribute] T>//on generic parameters{    //Apply on field[Field:myattribute]PrivateString _mystring; //applied on the construction method[Method:myattribute] PublicAttributeTargets () {}//Apply to Attributes[Property:myattribute] PublicString MyString {Get        {            return_mystring; }    }    //Apply on Method[return: MyAttribute] PublicString Format (//applied on the method parameter[Param:myattribute]string F] {        return NULL; }    //apply on an event[Event: MyAttribute] Public EventEventHandler MyEvent;}/// <summary>///an empty feature///available for all elements/// </summary> Public classmyattribute:system.attribute{} Public classmainclass{Static voidMain (string[] args) {    }}


3 There are several ways to know whether an element declares an attribute

System.Attribute.IsDefined

System.Attribute.GetCustomAttribute

System.Attribute.GetCustomAttributes

System.Reflection.CustomAttributeData

Example:

[My ("getattributes")]    classGetAttributes {Static voidMain (string[] args) {Type AttributeType=typeof(MyAttribute); Type ThisClass=typeof(getattributes); //using the IsDefined method            BOOLdefined =attribute.isdefined (ThisClass, attributetype); Console.WriteLine ("does the GetAttributes type declare the MyAttribute attribute: {0}", defined.            ToString ()); //using the Attribute.GetCustomAttribute methodAttribute att =Attribute.GetCustomAttribute (ThisClass, attributetype); if(Att! =NULL) {Console.WriteLine ("the GetAttributes type declares the MyAttribute feature. "); Console.WriteLine ("name is: {0}", ((MyAttribute) att).            Name); }            //using the Attribute.GetCustomAttributes methodattribute[] Atts =attribute.getcustomattributes (ThisClass, attributetype); if(Atts. Length >0) {Console.WriteLine ("the GetAttributes type declares the MyAttribute feature. "); Console.WriteLine ("name is: {0}", ((myattribute) atts[0]).            Name); }            //using the System.Reflection.CustomAttributeData typeilist<customattributedata> list =customattributedata.getcustomattributes (ThisClass); if(list. Count >0) {Console.WriteLine ("the GetAttributes type declares the MyAttribute feature. "); //Note that it is possible to analyze an attribute, but not to get its instanceCustomAttributeData Attdata = list[0]; Console.WriteLine ("the name of the attribute is: {0}", Attdata.                Constructor.DeclaringType.Name); Console.WriteLine ("the attribute is constructed with {0} parameters. ", Attdata.            Constructorarguments.count);        } console.read (); }    }    /// <summary>    ///a simple feature/// </summary>[AttributeUsage (AttributeTargets.All)] Public Sealed classMyattribute:attribute {PrivateString _name;  PublicMyAttribute (String s) {_name=s; }         PublicString Name {Get            {                return_name; }        }    }

Output:

Does the getattributes type declare the MyAttribute attribute: True
The GetAttributes type declares the MyAttribute feature.
Name is: getattributes
The GetAttributes type declares the MyAttribute feature.
Name is: getattributes
The GetAttributes type declares the MyAttribute feature.
The name of the attribute is: myattribute
There are 1 parameters for constructing a property.

Whether 41 elements can be repeated to declare the same feature

When an attribute declares the AttributeUsage attribute and the AllowMultiple property is set to True, the attribute can be declared multiple times on the same element, otherwise the compiler will be presented with an error.

Example:

[My ("Class1")] [My ("Class2")] [My ("Class1")]    classAllowMultiple {Static voidMain (string[] args) {        }    }    /// <summary>    ///Using AttributeUsage to limit the scope of use///and allow multiple declarations on the same element/// </summary>[AttributeUsage (attributetargets.class,allowmultiple=true)]    classMyattribute:attribute {PrivateString _s;  PublicMyAttribute (String s) {_s=s; }    }

Reprint please specify the source:

Jesselzj
Source: http://jesselzj.cnblogs.com

. NET Fundamentals (18) 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.