. NET attributes and attributes (RPM)

Source: Internet
Author: User
Tags naming convention

1. Introduction

attribute is. NET Framework introduces a technical highlight, so it is necessary to take some time to walk into an entrance to discover attribute presenting illegal weapons. Because the. NET framework uses a lot of custom features to accomplish code conventions, [Serializable], [Flags], [DllImport], [AttributeUsage] These constructs, I believe we have seen it, So do you know the technology behind it.

The mention of features, due to the historical reasons for advanced language development, is reminiscent of another familiar name: attributes. Attributes and attributes tend to confuse the conceptual impact of a beginner or a person moving from C + + to C #. So, what are attributes, what are attributes, the concepts and differences between the two, usage and examples, will be done in this article with a general summary and comparison, hoping to bring you the understanding of the harvest. In addition, the main topic of this article is the introduction of characteristics, the focus of the attribute is on the comparison between the two, more discussion about the attributes will be discussed in detail in another topic, please pay attention.

2. Concept Introduction

2.1. What are features?

MADN is defined as: The common language runtime allows the addition of a description declaration of similar keywords, called attributes, which labels elements in the 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.

We summarize briefly as follows: Custom feature attribute, essentially a class that provides associated additional information to the target element and obtains additional information in a reflection manner at run time. The specific feature implementation approach, which continues in the next discussion.

2.2. What is a property?

Attributes are the basic concepts of object-oriented programming, providing access encapsulation of private fields, and the use of the get and set accessor methods in C # for the operation of readable writable properties, providing a secure and flexible data access encapsulation. The concept of attributes, not the focus of this article, and believe that most of the technical staff should have a clear concept of attributes. The following is an example of a simple property:

  

2.3. Differences and comparisons

By clarifying the concepts and historical backtracking, we know that the attributes and attributes are only in the name of the dispute, on MSDN on the Chinese interpretation of attribute is even a property, but I agree with more commonly called: Features. In terms of function and application, there is not too much fuzzy concept crossover, so there is no need to compare the similarities and differences of its application. In this paper, the concept of the characteristics of the focus, to discuss its application of the occasion and rules.

I understand that the custom feature is to add additional information to the target element, which can be datasets, modules, classes, properties, methods, and even function parameters, similar to annotations, but can be obtained by reflection at run time. Custom features are mainly used in serialization, compiler directives, design patterns, and so on.

3. General rules

Custom attributes can be applied to a target element such as an assembly (assembly), module (modules), type (type), property, Event (field), method, parameter (param), return value ( return), should be all.

Custom features are presented in [,] form, placed next to each other, multiple attributes can be applied to the same element, and attributes are separated by commas, and the following expression rules are valid: [attributeusage][flags], [AttributeUsage, Flags], [flags, Attibuteusageattribute], [AttributeUsage (), Flagesattribute ()]

The Attibute instance is initialized at the compile time, not the run time.

C # allows the specified prefix to represent the target element to which the attribute is applied, which is recommended because explicit processing can eliminate the two semantics that might result. Example: Using System;

Using System;

Namespace Anytao.net
{
[Assembly:myattribute (1)]//apply to Assembly
[Moduel:myattribute (2)]//Apply to Module
Pubic class Attribute_how2do
{
//
}
}

Custom attribute types must be inherited directly or indirectly from the System.Attribute class, and the type must have a public constructor to create its instance.

All custom attribute names should have a attribute suffix, which is a customary convention.

Custom features can also be applied to other custom features, which is also well understood, because the custom feature itself is a class that adheres to the public rules of the class. For example, many times our custom custom features apply the AttributeUsageAttribute feature to control how the newly defined features are applied. [AttributeUsageAttribute (Attributetarget.all),

[AttributeUsageAttribute (Attributetarget.all),
AllowMultiple = True,
inherited = True]
Class MyNewAttribute:System.Attribute
{
//
}

Custom features do not affect any of the features of the application element, but only the qualities that the element has.

All non-abstract attributes must have public access restrictions.

Features are commonly used in compiler directives, breaking down # define, #undefine, #if, #endif的限制, and more flexible.

Custom features are often used to obtain code comment information at run time, with additional information to optimize debugging.

Custom features can be applied in certain design patterns, such as Factory mode.

Custom features are also commonly used for bit markers, unmanaged function tags, method discard tokens, and other aspects.

4. Application of features

4.1. Common Features

Common features, i.e.. NET has been provided by the intrinsic characteristics, in fact. NET Framework has provided a wealth of inherent characteristics by us to play, the following highlights I think the most commonly used, the most typical of the inherent characteristics of a simple discussion, of course, this is only my opinion, but also insignificant. I would like to know the characteristics, or from here as a starting point, from the classic of. NET to start, perhaps a shortcut to learn, hoping to give you a revelation.

AttributeUsage

The AttributeUsage attribute is used to control how custom attributes are applied to the target element. For AttributeTargets, AllowMultiple, inherited, Validon, see sample descriptions and other documentation. We've done quite a bit of introductions and examples, and we're still learning more about it in practice.

Flags

Use the flags attribute to treat enumerated values as bit markers, rather than as individual values, for example:

Enum Animal
{
Dog = 0x0001,
Cat = 0x0002,
Duck = 0x0004,
Chicken = 0x0008
}

As a result, the following implementations are fairly easy to

Animal animals = Animal.dog | Animal.cat;
Console.WriteLine (Animals. ToString ());

Please guess what the result is: "Dog, Cat." If there is no special flags, the result will be "3". The bit marks will also be explained in the follow-up chapters of this series, only to explore the stops.

DllImport

The DllImport feature allows us to invoke unmanaged code, so we can use the DllImport feature to introduce calls to WIN32 API functions, which are undoubtedly a lifesaver for programmers accustomed to unmanaged code.

Using System;
Using System.Runtime.InteropServices;

Namespace Anytao.net
{
Class MainClass
{
[DllImport ("User32.dll")]
public static extern int MessageBox (int hparent, string msg, string caption, int type);

static int Main ()
{
Return MessageBox (0, "How to use attribute. NET", "Anytao_net", 0);
}
}
}

Serializable

Serializable characteristics indicate that the applied elements can be serialized (serializated), serialization and deserialization is another topic that can be discussed in depth, where we only propose concepts, in-depth research to be presented on a special topic, confined to space, this does not repeat.

Conditional

The conditional attribute, used for conditional compilation, is used during debugging. NOTE: Conditional cannot be applied to data members and properties.

There are other important features, including: Description, DefaultValue, Category, ReadOnly, browerable, etc., there is time to study in depth.

4.2. Custom Features

Since attribute is essentially a class, then we can customize more specific attribute to meet the personalization requirements, as long as the above 12 rules, to implement a custom feature is actually very easy, the typical implementation method is:

Defining attributes

[AttributeUsage (AttributeTargets.Class |
AttributeTargets.Method,
inherited = True)]
public class TestAttribute:System.Attribute
{
Public Testattribute (String message)
{
throw new Exception ("Error:" + message);
}
public void Runtest ()
{
Console.WriteLine ("Testattribute here.");
}
}

Apply target element [Test ("Error here")]

[Test ("Error here.")]
public void Cannotrun ()
{
//
}

Get element Additional Information

If there is no mechanism to get attribute additional information during the run time, then attribute has no meaning. So. NET in the implementation of the reflection mechanism to obtain attribute information at run time, the implementation method is as follows:

public static void Main (string[] args)
{
Tester t = new Tester ();
T.cannotrun ();

Type tp = typeof (Tester);
Testattribute Myatt = (testattribute) attribute.getcustomattribute ((MemberInfo) TP, typeof (Testattribute));
Myatt.runtest ();
}

5. Classic example

5.1 A piece of cake

Don't say anything, read the notes.

Using System;
Using System.Reflection; Using reflection technology to obtain characteristic information

Namespace Anytao.net
{
Custom features can also be applied to other custom features,
Apply AttributeUsage to control how new defined features are applied
[AttributeUsageAttribute (AttributeTargets.All,//can apply any element
AllowMultiple = True,//Allow multiple applications
inherited = False)]//Do not inherit to a derived class
attribute is also a class,
Must inherit from the System.Attribute class,
The naming convention is: "Class name" +attribute.
public class MyselfAttribute:System.Attribute
{
Defining fields
private string _name;
private int _age;
private string _memo;

You must define its constructor if you do not define a compiler that provides an argument-free default constructor
Public Myselfattribute ()
{
}
Public Myselfattribute (string name, Int. age)
{
_name = name;
_age = age;
}

Defining properties
Obviously attributes and attributes are not the same thing.
public string Name
{
get {return _name = = null? string. Empty: _name; }
}

public int Age
{
get {return _age;}
}

public string Memo
{
get {return _memo;}
set {_memo = value;}
}

Defining methods
public void ShowName ()
{
Console.WriteLine ("Hello, {0}", _name = = null?) "World": _name);
}
}

Apply a custom attribute
You can use myself or Myselfattribute as the attribute name
You can assign a value to a property memo
[Myself ("Emma", +, Memo = "Emma is my good Girl.")]
public class Mytest
{
public void SayHello ()
{
Console.WriteLine ("Hello, My.net World");
}
}

public class Myrun
{
public static void Main (string[] args)
{
How to determine attribute information with reflection
Type tp = typeof (Mytest);
MemberInfo info = TP;
Myselfattribute myattribute =
(Myselfattribute) Attribute.GetCustomAttribute (Info, typeof (Myselfattribute));
if (myattribute! = null)
{
Hey, look at the comments at run time, isn't it cool
Console.WriteLine ("Name: {0}", myattribute.name);
Console.WriteLine ("Age: {0}", myattribute.age);
Console.WriteLine ("Memo of {0} is {1}", Myattribute.name, Myattribute.memo);
Myattribute.showname ();
}

Multi-point reflection
Object obj = Activator.CreateInstance (typeof (Mytest));

MethodInfo mi = TP. GetMethod ("SayHello");
Mi. Invoke (obj, null);
Console.ReadLine ();
}
}
}

Don't think about it, try it yourself.

5.2 Stone of his mountain

MSDN believes that the feature (Attribute) describes how to serialize data, specify the attributes used to enforce security, and limit the optimizations of the just-in-time (JIT) compiler so that the code is easy to debug. Properties (Attribute) can also record file names or code authors, or control the visibility of controls and members during the form development phase.

Dudu Boss Collection of articles, "attribute application in. NET programming", give you a lot of inspiration for the application, it is worth studying.

Comrade Alexander's series, "Teach you to write Orm (vi)", also has a very good interpretation.

Idior's article "Remoting basic principle and its extension mechanism" also has the harvest, therefore complements.

6. Conclusion

attribute is a major feature of. NET introduction, but in the blog park is not a lot of discussion, so come up with their own experience to share, I hope that the technical points for a presenting illegal weapons guide. Deeper applications, such as serialization, program security, and design patterns, can all be mined with sparkling gold, which is. NET in the field of technology to bring about the change of charm bar. I hope that we can speak freely, to improve and supplement the author in this aspect of the incomplete and cognitive not in-depth, it will be the author's greatest encouragement and motivation.

Other reference materials: http://www.cnblogs.com/atomplus/archive/2009/04/21/1440371.html
Http://www.cnblogs.com/hyddd/archive/2009/07/20/1526777.html

. NET attributes and attributes (RPM)

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.