Do your own ormapping Framework----Third Talk about attribute

Source: Internet
Author: User
Tags protected constructor

In this ormapping series, the implementation of this framework is based on the use of this attribute. Below or to get something, let small partners to attribute this thing has a better understanding, I also do not write, find a write can also be sorted down to everybody understand under.

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. [AttributeUsage (AttributeTargets.Class, AllowMultiple = False, inherited = False)]public Class Helpattribute:attribute {Public HelpAttribute (String description_in{this.description = description_in;}protected String description;Public String Description{get {return this.description; }  }}

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. [Help ("This is a do-nothing class")]//here to workpublic class anyclass{ [Help ("This is a do-nothing method")]//error because the previous definition cannot be marked on the methodspublic void Anymethod () {}}

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. [Help ("This is a do-nothing class")] [Help ("It contains a do-nothing method")]public class Anyclass{[help ("This was a do-nothing method")]//error public void A Nymethod () {}}

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. }

We are basically used in the back of the same way, and further into the point is also a truth, original aim, all a truth.

Make your own ormapping Framework----Third talk about attribute

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.