C # properties (Attribute) Details

1 , what is Atrribute  First of all, we certainly Attribute is a class below msdn documentation is its description:

The common language runtime allows you to add a statement describing similar keywords, called attributes, its program elements are labeled, such as type, fields, methods and attributes. Metadata Attributes and Microsoft .NET Framework files stored together, can be used to describe your code to the runtime or to affect application behavior when the program is running.

In .NET, Attribute is used to process a variety of problems, such as serialization, the security feature of the program, preventing in-time compiler program code can be optimized for the code easier to debug and the like. Here, let's look at a few properties in the use of the standard .NET, later on we'll come back to this discussion Attribute class itself. (Text of the code written in C #, but the same applies to all .NET-based all languages)

2 , the Attribute as a compiler directive

There is a certain amount of compiler directives in C #, such as: #define DEBUG, #undefine DEBUG, #if like. These instructions specific to C #, and is fixed in number. Attribute is used as the compiler directive is an unlimited number. For example, the following three Attribute:

   Conditional: from conditional compilation role only condition is satisfied, it is allowed code compiler to compile. Generally used when debugging a program.

   DllImport: .NET used to mark a non-function indicates that the method is defined in an external DLL.

   Obsolete: This attribute is used to mark the current methods have been abandoned and no longer used.

The following illustrates the use of the above three properties:

 

 

 1 #define  DEBUG  // here defined conditions

 2    

 3using System;

 4using System.Runtime.InteropServices;

 5using System.Diagnostics;

 6    

 7namespace AttributeDemo

 8{

 9   class MainProgramClass

10   {

11 

12      [DllImport("User32.dll")]

13      public static extern int MessageBox(int hParent, string Message, string Caption, int Type);

14     

15      static void Main(string[] args)

16      {

17         DisplayRunningMessage();

18         DisplayDebugMessage();

19     

20         MessageBox(0,"Hello","Message",0);

21     

22         Console.ReadLine();

23      }

24     

25      [Conditional("DEBUG")]

26      private static void DisplayRunningMessage()

27      {

28          Console.WriteLine ( " start running Main subroutine current time is. " + DateTime.Now);

29      }

30  

31      [Conditional("DEBUG")]

32      //[Obsolete("Don't use Old method, use New method", true)] 

33      [Obsolete]

34      private static void DisplayDebugMessage()

35      {

36          Console.WriteLine ( " start Main subroutine " );

37      }

38   }

39}  

 

If a program element of a previously declared an Attribute, then it indicates that the Attribute is applied to the element, the previous code, [the DllImport] is applied to the MessageBox function, [the Conditional] applied to DisplayRuntimeMessage method and DisplayDebugMessage method, [The Obsolete] applied to DisplayDebugMessage method.

Attribute of three according to the instructions related to the above, we can guess the output generated when the program is running: DllImport Attribute indicates the MessageBox function is User32.DLL in, so that we can call this function the same as the internal method.

The important point is that Attribute is a class, it is also a DllImport class Attribute class is at compile time is instantiated, rather than the usual class as it is instantiated at run time. Attribute instantiated based on the design of the Attribute class parameters may, also be used without parameters, with such parameters to DllImport "User32.dll" a. Conditional to meet the conditions of the code defines the parameters to be compiled, if not defined DEBUG, then the method will not be compiled, readers can comment out the line #define DEBUG to see the results output (release version, Conditional Debug version of the debug always true). Obsolete shows DispalyDebugMessage method is outdated, it has a better way to replace it, when our program calls a statement of Obsolete method, the compiler will give information, there are two other overloaded Obsolete version. You can refer to msdn for a description of the ObsoleteAttribute class.

3 , the Attribute class

Attribute addition to those provided by the derived class .NET, we can customize our own Attribute, all Attribute custom must derive from Attribute class. Now we look at the details of Attribute class:

protected Attribute (): protected constructor can only be called Attribute-derived class.

Three static methods:

static Attribute GetCustomAttribute (): This method has eight kinds overloaded version, which is used to remove the specified type is applied to a class member Attribute.

static Attribute [] GetCustomAttributes (): This method has 16 overloaded version of the specified type in the array is used to remove the Attribute class member is applied.

static bool IsDefined (): the eight kinds of heavy-duty version to see if the specified type of custom attribute is applied to the members of the class above.

Examples of methods:

bool IsDefaultAttribute (): If the value of the Attribute is the default value, then returns true.

bool Match (): Attribute that indicates whether this instance equals a specified object.

Public property: TypeId: obtain a unique identifier, the identifier is used to distinguish different instances of the same Attribute.

We simply introduced the Attribute class methods and properties, and some are inherited from the object. Here it is not listed.

Here's how to customize a Attribute: Custom Attribute does not require a special knowledge, fact and write a class almost. Since Attribute definition must be directly or indirectly derived from the Attribute class, such as:

public MyCustomAttribute : Attribute { ... }

It should be noted that the Attribute naming conventions, that is, your Attribute class name + "Attribute", when your Attribute applied to an element of a program, the compiler to find the definition of your Attribute, if not found , then it will look + definitions of Attribute "Attribute name." If you are not found, then the compiler error.

 

4 , or using the defined control features

Attribute for a custom, you can define your type Attribute by the applied elements of AttributeUsage Attribute. Code form as follows:

[AttriubteUsage ( parameter )] public  custom Attribute: Attribute {...}

 Interestingly enough, AttributeUsage itself is an Attribute, which is specifically applied. AttributeUsage naturally derived from Attribute in the Attribute Attribute class that has a constructor with parameters, this parameter is AttributeTargets enumerated type. Here is the definition of AttributeTargets:

 

 1public enum AttributeTargets

 2{

 3   All=16383,

 4   Assembly=1,

 5   Module=2,

 6   Class=4,

 7   Struct=8,

 8   Enum=16,

 9   Constructor=32,

10   Method=64,

11   Property=128,

12   Field=256,

13   Event=512,

14   Interface=1024,

15   Parameter=2048,

16   Delegate=4096,

17   ReturnValue=8192

18}     

 

AttributeTarges as the value of the parameter allows multiple combinations worth by "or" operation, if you do not specify parameters, the default parameter is the All. AttributeUsage addition Attribute inheritance of methods and properties, also defines the following three properties:

AllowMultiple: to read or set the attribute indicates whether a plurality of Attribute may be applied to a program element.

Inherited: to read or set the attribute Attribute indicates whether to apply the derived class may be inherited or overloaded.

ValidOn: to read or set the property that indicates the type of Attribute elements may be applied.

Let's do some practical things. We will be placed in front of the characteristics AttributeUsage Help Help features to look forward to control the use of property in 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 us look at AttributeTargets.Class. It provides the Help properties can only be placed in front of the class. This also means that the following code will generate an error:

 

1[Help("this is a do-nothing class")] 

2public class AnyClass 

3

4[Help("this is a do-nothing method")] //error 

5public void AnyMethod() 

6

7

8}

 

  The compiler reports the following error:

  AnyClass.cs: Attribute 'Help' is not valid on this declaration type.

  It is valid on 'class' declarations only.

 

  We can use the Help feature is to allow AttributeTargets.All placed in front of any program entity. 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 the following AllowMultiple = false. It specifies the characteristics of the placement can not be repeated many times.

 

1[Help("this is a do-nothing class")] 

2[Help("it contains a do-nothing method")] 

3public class AnyClass 

4

5[Help("this is a do-nothing method")] //error 

6public void AnyMethod() 

7

8

9}

 

  It produces a compile-time error.

  AnyClass.cs: Duplicate 'Help' attribute

  Ok, now let's talk about this last property. Inherited, it shows that when the characteristic is placed on a base class, it can be inherited by the derived class.

 

1[Help("BaseClass")] 

2public class Base 

3

4

5

6public class Derive : Base 

7

8}

9

 

  There will be 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 ]

  The first case:

  If we query (Query) (Later we will see how to query the properties of a class at runtime) Derive class, we will find the Help feature does not exist, because the inherited property is set to false.

  The second case:

  The first case and the same, because the inherited also set to false.

  The third case:

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

 

1[Help("BaseClass")] 

2public class Base 

3

4

5[Help("DeriveClass")] 

6public class Derive : Base 

7

8}

 

  Now we come to inquire about the Help feature, we can only get property derived class, because inherited is set to true, but AllowMultiple was set to false. Help therefore the characteristics of the base class is a derived class Help characteristics covered.

  Fourth case:

  Here, we will find Help characteristics of both the derived class base class, also has its own Help feature because AllowMultiple is set to true.

 

So far, we have introduced the related Attribute classes and their code format. You will want to know in the end how to use the Attribute in your application, if only the contents described earlier, or not enough Attribute what practical value, then begins with the following sections we will introduce several different uses of Attribute, I am sure you will have a new understanding Attribute.

Released six original articles · won praise 43 · views 570 000 +

Guess you like

Origin blog.csdn.net/hany3000/article/details/88063448