. Net attribute Features

Source: Internet
Author: User
Tags protected constructor

1. What is Atrribute
First, we are sure that attribute is a class, and here is a description of it in the MSDN documentation:
The common language runtime allows you to add a descriptive declaration like a keyword, called attributes, that labels elements in your program, such as types, fields, methods, and properties. Attributes and Microsoft. NET Framework file metadata are saved together to describe your code to the runtime, or to affect the behavior of your application as it runs.

In. NET, attribute is used to handle a variety of problems, such as serialization, the security features of the program, preventing the immediate compiler from optimizing program code, code debugging, and so on. Next, let's look at some of them. NET in the use of the standard attributes, we'll go back to discussing the attribute class itself later. (The code in this article is written in C #, but the same applies to all based. NET in all languages)

3, Attribute class
Apart from. NET provided by those attribute derived classes, we can customize our own attribute, all custom attribute must derive from the attribute class. Now let's look at the details of the attribute class:

Protected Attribute (): A protected constructor that can only be called by a derived class of Attribute.

Three static methods:

static Attribute GetCustomAttribute (): This method has 8 overloaded versions, which are used to remove Attribute that are applied to a specified type on a class member.

Static attribute[] GetCustomAttributes (): This method has 16 overloaded versions that take out the Attribute array that is applied to the specified type on the class member.

static bool IsDefined (): consists of eight overloaded versions, to see whether a custom attribute of the specified type is applied to the members of the class.

Example method:

BOOL Isdefaultattribute (): Returns True if the value of attribute is the default value.

BOOL Match (): Indicates whether the attribute instance is equal to a specified object.

Public properties: TypeId: Get a unique identifier that is used to distinguish between different instances of the same attribute.

We simply introduced the methods and properties of the attribute class, and some inherited it from object. It's not listed here.

Here's how to customize a attribute: Customizing a attribute doesn't require special knowledge, it's almost like writing a class. The custom attribute must derive directly or indirectly from the attribute class, such as:

Public Mycustomattribute:attribute {...}

It is necessary to point out that the Attribute naming specification, which is your Attribute class name + "Attribute", when your Attribute is applied to the elements of a program, the compiler first looks for your Attribute definition, if not found, Then it looks for the definition of the "attribute name" +attribute. If none are found, then the compiler will error.

4. Defining or controlling the use of features

For a custom attribute, you can limit the type of elements that your attribute imposes by AttributeUsage attribute. The code form is as follows:
[Attriubteusage (parameter setting)] public custom Attribute:attribute {...}

The value of Attributetarges as a parameter allows multiple combinations to be made by "or" operations, and if you do not specify a parameter, the default parameter is all. AttributeUsage In addition to inheriting the methods and properties of attribute, the following three properties are defined:

AllowMultiple: Reads or sets this property to indicate whether multiple attribute can be applied to a program element.

inherited: Reads or sets this property, indicating whether the applied attribute can be inherited or overloaded by a derived class.

Validon: Reads or sets this property, indicating the type of element that the attribute can be applied to.

Let's do some practical things. We will place the AttributeUsage feature in front of the help feature to look forward to controlling the use of the assist feature with its assistance.

Hide line number copy code ? This is a program code.
    1. [AttributeUsage (AttributeTargets.Class, AllowMultiple = False, inherited = False)]
    2. public class Helpattribute:attribute
    3. {
    4.     Public HelpAttribute (String description_in)
    5.     {
    6.         this.description = description_in;
    7.     }
    8.     protected String description;
    9.     Public String Description
    10.     {
    11.         Get
    12.         {
    13.             return this.description;
    14.         }
    15.     }
    16. }

Code Discussion
    • The AttributeUsage property specifies the language element that the property can be applied to.
    • An attribute class is a public class derived from System.Attribute and has at least one public constructor.
    • Attribute classes have two types of parameters:
      • Positional parameters, which must be specified each time the property is used. The positional parameter is specified as the constructor parameter of the attribute class. In the example above, the URL is a positional parameter.
      • "Named parameters", optional. If you specify a named parameter when you use the property, you must use the name of the parameter. Define named parameters by including non-static fields or properties. In the example above, Topic is a named parameter.

Let's take a look at attributetargets.classfirst. It specifies that the Help feature can only be placed in front of class. This also means that the following code will produce an error:

Hide line number copy code ? This is a program code.
    1. [Help ("This is a do-nothing class")]
    2. public class Anyclass
    3. {
    4.     
    5.     public void Anymethod ()
    6.     {
    7.     }
    8. }

The compiler reported an error as follows:

AnyClass.cs:Attribute ' help ' isn't valid on this declaration type.

It is valid on ' class ' declarations only.

We can use AttributeTargets.All to allow the Help attribute to be placed before any program entities. The possible values are:

Assembly,module,class,struct,enum,constructor,method,property,field,event,interface,
Parameter,delegate.

all = Assembly | Module | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate,

Classmembers = Class | Struct | Enum | Constructor | Method | Property | Field | Event | Delegate | Interface)

Consider AllowMultiple = False below. It specifies that the attribute cannot be placed repeatedly.

Hide line number copy code ? This is a program code.
    1. [Help ("This is a do-nothing class")]
    2. [Help ("It contains a do-nothing method")]
    3. public class Anyclass
    4. {
    5.     
    6.     public void Anymethod ()
    7.     {
    8.     }
    9. }

It produces a compile-time error.

AnyClass.cs:Duplicate ' help ' attribute

Ok, now let's discuss the final attribute. Inherited, which indicates whether it can be inherited by a derived class when the attribute is placed on a base class.

Hide line number copy code ? This is a program code.
    1. [Help ("BaseClass")]
    2. public class Base
    3. {
    4. }
    5. public class Derive:base
    6. {
    7. }

There are four possible combinations of these:

[AttributeUsage (AttributeTargets.Class, AllowMultiple = False, inherited = False]

[AttributeUsage (AttributeTargets.Class, AllowMultiple = true, inherited = False]

[AttributeUsage (AttributeTargets.Class, AllowMultiple = False, inherited = True]

[AttributeUsage (AttributeTargets.Class, AllowMultiple = true, inherited = True]

First case:

If we query (we will see later how to query the attributes of a class at run time) derive class, we will find that the Help attribute does not exist because the inherited property is set to False.

Second case:

Same as in the first case, because inherited is also set to false.

The third case:

To explain the third and fourth cases, let's first add the point code to the derived class:

Hide line number copy code ? This is a program code.
    1. [Help ("BaseClass")]
    2. public class Base
    3. {
    4. }
    5. [Help ("Deriveclass")]
    6. public class Derive:base
    7. {
    8. }

Now let's look at the Help feature, we can only get the properties of the derived class, because inherited is set to true, but AllowMultiple is set to false. Therefore, the help attribute of the base class is overridden by the derived class Help feature.

Fourth case:

Here, we will find that the derived class has both the help attribute of the base class and its own Help feature, because AllowMultiple is set to true.

            • Accessing properties through Reflection

After a property is associated with a program element, you can use the Reflection query property to exist and its value. The primary reflection method of a query property is contained in the System.Reflection.MemberInfo class (the GetCustomAttributes method family). The following example shows the basic method of getting access to a property using reflection:

Hide line number copy code ? This is a program code.
    1. System.Reflection.MemberInfo info = typeof (Help);
    2. object[] Attributes = info. GetCustomAttributes (TRUE);
    3. for (int i = 0; i < attributes. Length; i++)
    4. {
    5.     System.Console.WriteLine (Attributes[i]);
    6. }

1. Attribute attribute cannot be confused with attribute property, which is a completely different two thing.

2. Attributes attribute the contents of the class or method identifier, which can be obtained through reflection when the program is running.

For example 1:. NET added unit test class, there is a testclass identity, inside the method has TestMethod identity, when the user wants to run the test case, a little button, all the test case class, each class test methods are displayed in front of the The user is free to choose which test class to run and which test methods in the class, which is how to do this, I believe that is. NET by reflection to get all the TestClass identity of the class, made a list to display to the user, click on this class, And then through the reflection of all the class has a TestMethod identity method, and then display to the user, so do.

For example 2:[obsolete ("This is an obsolete method")] added to a method or class before the compiler can prompt you this is an outdated method, how to do it? It must be the compiler to scan the method before you have this flag, if any, to record it, show it.

3. Characteristics attribute This thing is similar to static constants, belongs to the class all, does not belong to each particular object, if has no characteristic attribute this thing, many things will be difficult to do.

4. Built-in three important features attribute and an enum enum AttributeTargets

AttributeUsage
ComVisible
SerializableAttribute

The latter two features are actually very simple code, which is a flag, such as SerializableAttribute.

Namespace System
{
[AttributeUsage (AttributeTargets.Class | attributetargets.struct | Attributetargets.enum | Attributetargets.delegate, inherited = False)]
[ComVisible (True)]
public sealed class Serializableattribute:attribute
{
public SerializableAttribute ();
}
}

AttributeUsage is more important, there are three important parameters can be set,

AttributeTargets This is an enumeration that lists the custom attributes that can be used to decorate who, Class, interface, or all, with multiple intermediate | partitions. If you decorate a interface with a feature that only allows AttributeTargets.Class , it is doomed to compile.

[AttributeUsage (attributetargets.assembly | AttributeTargets.Class | attributetargets.struct | Attributetargets.enum | AttributeTargets.Method | Attributetargets.property | Attributetargets.field | Attributetargets.interface | Attributetargets.delegate, inherited = False)]

AllowMultiple Indicates whether this attribute can be placed repeatedly to decorate a method or class.

[Lzd (Name = "Animal")]
[Lzd (Name = "Animals")]
public class Animal
{
...
}

Inherited indicates whether it can be inherited

If inherited = False, the derived class cannot inherit the attribute.

If inherited = True, derived classes can inherit attributes, but if AllowMultiple = False, then if the derived class itself adds the same attribute, the attributes of the parent class are masked.

. Net attribute 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.