Difference between attribute and property translation the scope of use of attribute

Source: Internet
Author: User

Translation differences between Attribute and Property

Attribute is generally translated as"Features", Property is still translated as"Attribute".


Attribute isWhat

Attribute is a modifier that can be freely defined by the user and can be used to modify various objects to be modified.

In short, attribute is an "attachment"-just like an oyster adsorption on the bottom of a ship or on a reef.

These attachments are used to append additional information to their attachments (the information is stored in the body of the attachments) -- for example, "this class is written by me" or "this function has encountered problems before.


Role of Attribute

The role of feature attribute isAdd metadata.
Metadata can be supported by tools. For example, the compiler uses metadata to assist compilation, and the debugger uses metadata to debug programs.


Difference between Attribute and Annotation

○ Annotation is a description of the program source code. The main purpose is to show it to people. The program will be discarded by the compiler when it is compiled. Therefore, it does not affect the execution of the program.

○ Attribute is a part of the program code. It will not only be discarded by the compiler, but also be compiled into the metadata of the Assembly. When the program is running, you can extract the additional information from the metadata at any time to determine how the program runs.


In the project, there is a class jointly maintained by two programmers (Xiao Zhang and Xiao Li. This class acts as a "toolkit" (utilities (Just like the Math class in. NET Framework.), Which contains dozens of static methods. Half of these static methods are written by Xiao Zhang, and half are written by Xiao Li. Some static methods have encountered bugs during project tests and were subsequently corrected. In this way, we can divide these aspects into the following categories:

The purpose of classification is to test and obtain different results based on different categories. For example, count the workload of two people or perform regression tests on methods with bugs.

IfDo not use AttributeTo distinguish these four types of static methods, we can only describe them through annotations, but this method has many drawbacks;

IfUse Attribute, Distinguishing these four types of static methods will become much easier. The sample code is as follows:

# The macro definition of define buged // C # must appear before all code. Currently, only the buged macro is valid. Using system; using system. diagnostics; // note: this is to use the conditionalattribute feature namespace con_attribute {class program {static void main (string [] ARGs) contained in this namespace) {// although all methods are called, only those that meet the conditions will be executed! Toolkit. FUNA (); toolkit. funb (); toolkit. func (); toolkit. fund () ;}} class toolkit {[conditionalattribute ("Li")] // attribute name long note method [conditionalattribute ("buged")] public static void FUNA () {console. writeline ("created by Li, buged. ");} [conditional (" Li ")] // attribute name note method [conditional (" nobug ")] public static void funb () {console. writeline ("created by Li, nobug. ");} [conditionalattribute (" Zhang ")] // attribute name long note method [conditionalattribute (" buged ")] public static void func () {console. writeline ("created by Zhang, buged. ");} [conditional (" Zhang ")] // attribute name note method [conditional (" nobug ")] public static void Fund () {console. writeline ("created by Zhang, nobug. ");}}}


The running result is as follows:

Note: The running result is "# define buged" in the code.Macro definitionDetermined.



1. In this example, we use the attribute conditionalattribute, which is included inSystem. DiagnosticsNamespace. Apparently, most of its time is used for programDebuggingAndDiagnosis.

2. A group related to conditionalattributeC # macroThey seem to have nothing to do with the macros of C language, and must appear before all C # code. As the name suggests, conditionalattribute is used to determine conditions. Any method that is "attached" by conditionalattribute (or conditional) will be executed only when conditions are met.

3.AttributeJust like the bottom of a ship can be attached to manyOysterSimilarly, multiple conditionalattribute instances can be attached to a method. The writing format for attaching attribute to the target is very simple. Enclose the attribute with square brackets, and then write the attachment of the attribute. When multiple attributes are attached to the same object, the square brackets of these attributes are written one by one (or multiple attributes are written in one pair of square brackets ), and do not care about their order.

4. When using attribute, there are two types: "Long note" and "short note.


We can launch the above 3rd and 4th attributes. The usage of the following four attributes is completely equivalent:

// Note the [ConditionalAttribute ("LI")] [ConditionalAttribute ("NoBug")] public static void Fun () {Console. writeLine ("Created By Li, NoBug. ");} // note [Conditional (" LI ")] [Conditional (" NoBug ")] public static void Fun () {Console. writeLine ("Created By Li, NoBug. ");} // [Conditional (" NoBug ")] [Conditional (" LI ")] public static void Fun () {Console. writeLine ("Created By Li, NoBug. ");} // [Conditional (" NoBug "), Conditional (" LI ")] public static void Fun () {Console. writeLine ("Created By Li, NoBug. ");}


Attribute nature

From the code above, we can see that Attribute always appears together with the public and static keywords (Keyword.

Is using Attribute equivalent to defining a new Modifier (Modifier? Let's take a look!

The sample code is as follows:

# Define XG // C # The macro definition must appear before all code using system; using system. diagnostics; // note: this is to use the namespace con_attribute {class program2 {[conditional ("XG")] Static void fun () {console. foregroundcolor = consolecolor. yellow; console. writeline ("http://xugang.cnblogs.com");} static void main (string [] ARGs) {fun ();}}}


Use Microsoft's intermediate language anti-compiler to view the msil intermediate languageTargetMethod: void ()The method code is as follows:

We can see that:Attribute is essentially a class, which is finally instantiated on the attached target object.


After carefully observing the code of the intermediate language (msil), the facts covered by the C # Language become naked in the intermediate language (msil. And attribute has become no secret!

In the figure, red indicatesFun MethodAndModifier,Attribute does not appear here.

In the figure, blue refers to the callMscorlib. dllAssemblySystem. DiagnosticsNamespaceConditionalAttributeClassConstructor.

It can be seen that attribute is not a modifier, but a uniqueInstantiated class!


What are the unique characteristics of Attribute instantiation?

1. Its instance is used. Custom Declaration. View the intermediate language syntax and you will find that. m is specifically used to declare custom features.

2. the Attribute declaration is located before the real code (IL_0000 to IL_0014) in the function body.

This proves from the "bottom layer" that Attribute is not a "modifier", but a special class in instantiation mode.


Role of metadata

In the MSIL intermediate languageMetadata(Metadata) records the number of namespaces, classes, members in the class, and access levels of the members in the set. In addition, metadata exists in the form of text (that is, Unicode characters) and is used. NET Reflection technology can read them and form a tree chart in MSIL, the Object Browser view in VS, and the automatic code prompt function.The combination of metadata and reflection technology. An assembly (. EXE or. DLL) can use metadata contained in its own body to completely describe itself without having
With a large bundle of header files, this is called"Self-contained"Or"Self-descriptive".


Attribute instantiation

Just as oysters naturally need to be adsorbed on the reef or bottom of the ship, an Attribute instance must be "glued" to a specific target as soon as it is constructed.

Attribute instantiation syntax is quite weird, mainly reflected in the following three points:

1.Not usedNew OperationTo generate an instance.Call the constructor in square bracketsTo generate instances.

2.Square brackets are requiredNextPlaced on attachedBefore the target.

3.Because square brackets have limited space,NoConstruct an object as new and assign a value to the Property of the object.

ThereforeAttribute assignmentAlso inParentheses of the constructor.


And,Attribute instantiationNote:

1. Constructor'sThe parameter must be written.. You have to write a few because youDo not writeWordsThe instance cannot be constructed..

2. constructor ParametersOrder cannot be wrong. No function can be called to change the order of parameters unless it has a corresponding Overload ). Because the order is fixed, some books call it "positioning parameters" (I .e. "parameters with fixed numbers and positions ").

3. For Attribute instancesAttribute assignment is optional. It has a default value, and the order of attribute values is unrestricted. In some books, the attribute value parameter is "name parameter ".


Custom Attribute instance

Here, we do not use the various Attribute system features in. NET Framework, but define a brand new Attribute class from scratch.

The sample code is as follows:

Using System; namespace Con_Attribute {class Program3 {static void Main (string [] args) {// read AttributeSystem using Reflection. reflection. memberInfo info = typeof (Student); // obtain the information of the Student class through reflection. getCustomAttribute (info, typeof (holobby); if (hobbyAttr! = Null) {Console. writeLine ("Class Name: {0}", info. name); Console. writeLine ("interest type: {0}", hobbyAttr. type); Console. writeLine ("interest index: {0}", hobbyAttr. level) ;}}// note: "Sports" assigns a value to the constructor, and Level = 5 assigns a value to the attribute. [Holobby ("Sports", Level = 5)] class Student {[holobby ("Football")] public string transfer Sion; public string transfer sion {get {return transfer Sion ;} set {customization sion = value ;}}// we recommend that you name it HobbyAttributeclass holobby: Attribute // must be System. attribute Class is dangerous for the string whose base class {// parameter value is null. Therefore, you must assign public holobby (string _ type) to the constructor. // locate the parameter {this. type = _ type;} // interest type private string Type; public string type {get {return type;} set {type = value ;}// interest index private int level; public int Level {get {return level;} set {level = value ;}}}}

In the above exampleHolobby classOfConstructorOnly oneParametersTherefore, the "positioning parameters" are not fully reflected. You canHolobby classAdd moreAttribute, AndConstructorSet up moreParameters, Try it outAttribute
The sensitivity to the number of parameters and the parameter location.


Target to which Attribute can be attached

Attribute can attach its instanceTargetWhat about? The answer to this question is hidden in AttributeTargets.Enumeration type.

The set of values of this type is:

========================================================== ========================================================== ======================================

All Assembly Class Constructor

Delegate Enum event Field

Genericparameter interface method module

Parameter property returnvalue struct

========================================================== ========================================================== ======================================

A total of 16 values are allowed. The preceding table is in alphabetical order and does not represent the order of their actual values.

Use the following applet to view the integer corresponding to each enumeration value. The sample code is as follows:

using System;namespace Con_Attribute{class Program4{static void Main(string[] args){Console.WriteLine("Assembly/t/t/t{0}", Convert.ToInt32(AttributeTargets.Assembly));Console.WriteLine("Module/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Module));Console.WriteLine("Class/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Class));Console.WriteLine("Struct/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Struct));Console.WriteLine("Enum/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Enum));Console.WriteLine("Constructor/t/t/t{0}", Convert.ToInt32(AttributeTargets.Constructor));Console.WriteLine("Method/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Method));Console.WriteLine("Property/t/t/t{0}", Convert.ToInt32(AttributeTargets.Property));Console.WriteLine("Field/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Field));Console.WriteLine("Event/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.Event));Console.WriteLine("Interface/t/t/t{0}", Convert.ToInt32(AttributeTargets.Interface));Console.WriteLine("Parameter/t/t/t{0}", Convert.ToInt32(AttributeTargets.Parameter));Console.WriteLine("Delegate/t/t/t{0}", Convert.ToInt32(AttributeTargets.Delegate));Console.WriteLine("ReturnValue/t/t/t{0}", Convert.ToInt32(AttributeTargets.ReturnValue));Console.WriteLine("GenericParameter/t/t{0}", Convert.ToInt32(AttributeTargets.GenericParameter));Console.WriteLine("All/t/t/t/t{0}", Convert.ToInt32(AttributeTargets.All));Console.WriteLine("/n");}}}

The result is as follows:


Attributetargets uses another way of enumeration value-The identifier.
Except for the value of All, only one of the binary forms of each value is "1", and the other bits are "0 ".
If our Attribute requires both Class and Class methods to be attached. You can use the operator "|" in C # (that is, bitwise "or "). With it, we only need to write the code as follows:

AttributeTargets. Class | AttributeTargets. Method

Because the identifiers (that is, the unique "1") of the two enumerated values are staggered, you only need to evaluate or solve the problem by bit.

In this way, you can understand: Why?Attributetargets. AllThe value is32767.

By default, when we declare and define a new Attribute class, it can be attached to AttributeTargets. All.

In most cases, AttributeTargets. All meets your needs. However, if you have to limit it, you have to take some twists and turns.

For exampleHolobby classOfAttachment target RestrictionOnlyClassAndField", The sample code is as follows:

[AttributeUsage (AttributeTargets. Class, AttributeTargets. Field)] class holobby: Attribute // The System. Attribute Class must be used as the base class {// implementation of the holobby Class}

Here, the AttributeUsage is attached to the Attribute class. Attribute is essentially a class, and AttributeUsage also describes the types of holobby classes that can be attached.


Additional questions:

1. IfAttribute ClassAttached to a class, then thisAttribute ClassWill it followInheritance relationshipAlso attachedDerived classWhat about?

2. Can I attach one oyster to the same ship as one oyster?Attribute ClassOfMultiple instancesAttachedSame GoalWhat about?

Answer: Yes. The Code is as follows:

[AttributeUsage (AttributeTargets. Class | AttributeTargets. Field, Inherited = false, AllowMultiple = true)] class holobby: System. Attribute {// specific implementation of the holobby Class}

AttributeUsageAttribute used to modify attributeIn addition to controlling the modifier object, you can also determine whether the Attribute Modified by the modifier can be used with the Host"Genetics", And whether or notUse multiple instances to modify the same target!

That ModifierConditionalattributeWhat Will AttributeUsage look like? (The answer is in MSDN)

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.