Customization features and reflection usage

Source: Internet
Author: User

You can write feature classes to add custom features such as class, assembly, and method to describe and annotate the usage, modification, and functions of these assemblies and classes. so when we encapsulate the Assembly and apply this Assembly later, if we want to understand the methods and classes, we can use the reflection mechanism to read these features.
The custom feature is written to metadata and read at runtime, so that users can use it easily and make decisions based on specific situations.

--------------------------------------------------- (Convert )----------------------------------

Introduction

Attributes is a brand new declarative information. We can not only define design-level information (such as help file and URL for documentation) through features, but also run-time information (such as associating XML with class ), we can also use features to build self-describing components. In this tutorial, we will see how to create and add features to various program entities and how to obtain feature information in the runtime environment.

 

Definition

As described in msdn -----

"A feature is an additional declarative information assigned to a declaration ."

 

Use pre-defined features

In C #, there is a small set of predefined features. Before learning how to create custom features (custom attributes), let's take a look at how to use predefined features in our code.

 

Using system;
Public class anyclass
{
[Obsolete ("Don't use old method, use new method", true)]
Static void old (){}

Static void new (){}

Public static void main ()
{
Old ();
}
}
Let's take a look at the above example. In this example, we use the obsolete feature, which marks a program entity that should not be used again. The first parameter is a string that explains why the object is outdated and what entity should be used to replace it. Actually, you can write any text here. The second parameter tells the compiler to treat the obsolete program entity as an error. The default value is false, which means the compiler generates a warning.

When we try to compile the above program, we will get an error:

Anyclass. Old () 'is obsolete: 'don' t use old method, use new Method'
 

Custom features (M attributes)

Now let's take a look at how to develop our own features.

First, we need to derive our own feature class from system. Attribute (a class inherited from the system. Attribute abstract class, whether directly or indirectly inherited, will become a feature class. The declaration of a feature class defines a new feature that can be placed on the Declaration ).

Using system;
Public class helpattribute: attribute
{
}
Whether you believe it or not, we have established a custom feature. Now we can use it to describe existing classes as if we used the obsolete attribute above.

[Help ()]
Public class anyclass
{
}
Note: using the attribute suffix for a feature class name is a convention. However, when we add features to a program entity, whether or not to include attribute suffixes is our freedom. The compiler first looks for the added feature class in the derived class of system. attribute. If not, the compiler adds the attribute suffix to continue searching.

 

So far, this feature has not played any role. Next we will add something to make it more useful.

Using system;
Public class helpattribute: attribute
{
Public helpattribute (string descrition_in)
{
This. Description = description_in;
}
Protected string description;
Public String description
{
Get
{
Return this. description;

}
}
}
[Help ("This is a do-nothing class")]
Public class anyclass
{
}
In the above example, we added an attribute to the helpattribute feature class and we will search for it in the runtime environment in the subsequent sections.

Define or control the use of features

The attributeusage class is another predefined feature class that helps us control the use of our own custom features. It describes a custom feature such as and is used.

Attributeusage has three attributes, which can be placed before custom attributes. The first attribute is:

 

Validon

With this attribute, we can define the program entity before which the custom feature should be placed. All Program entities whose attributes can be placed are listed in attributetargets enumerator. Through the or operation, we can combine several attributetargets values.

 

Allowmultiple

This attribute marks whether our custom features can be repeatedly placed in the same program entity multiple times before.

 

Inherited

We can use this property to control the inheritance rules of custom features. It indicates whether our features can be inherited.

 

Let's do something practical. We will place the attributeusage feature before the help feature to control the use of the help feature with its help.

Using system;
[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;
}
}
}
Let's take a look at attributetargets. Class. It specifies that the help feature can only be placed before the class. This means that the following code will produce errors:

[Help ("This is a do-nothing class")]
Public class anyclass
{
[Help ("This is a do-nothing method")] // Error
Public void anymethod ()
{
}
}
The compiler reports the following errors:

Anyclass. CS: attribute 'help' is not valid on this declaration type.

It is valid on 'class' declarations only.

 

Attributetargets. All can be used to allow the help feature to be placed before any program entity. Possible values:

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. It specifies that features cannot be repeatedly placed multiple times.

[Help ("This is a do-nothing class")]
[Help ("It contains a do-nothing method")]
Public class anyclass
{
[Help ("This is a do-nothing method")] // Error
Public void anymethod ()
{
}
}
It produces a compilation error.

Anyclass. CS: duplicate 'help' attribute

 

OK. Now let's discuss the final attribute. Inherited indicates whether a feature can be inherited by a derived class when it is placed on a base class.

 

[Help ("baseclass")]
Public class base
{
}
 
Public class derive: Base
{
}
There are four possible combinations:

[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 (query) (we will see how to query the features of a class at runtime) The derive class will find that the help feature does not exist because the inherited attribute is set to false.

 

Case 2:

This is the same as the first case because inherited is also set to false.

 

Case 3:

To explain the third and fourth cases, add the vertex code to the derived class:

[Help ("baseclass")]
Public class base
{
}
[Help ("deriveclass")]
Public class derive: Base
{
}
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 feature of the base class is overwritten by the help feature of the derived class.

 

Case 4:

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

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.