[C #] just to briefly describe the features,

Source: Internet
Author: User
Tags map class

[C #] just to briefly describe the features,
Just to briefly describe the feature-Attribute

[Master] Anti-bone Zi (original address] http://www.cnblogs.com/liqingwen/p/5911289.html

Directory
  • Features
  • Features
  • Feature parameters
  • Feature goals
  • Common usage of features
  • Create custom features
  • Use reflection access features

 

1. Feature overview features provide powerful methods to associate metadata or declarative information with code (assembly, type, method, attribute, etc. After features are associated with program entities, you can use the "reflection" query feature during runtime.

Features have the following attributes:

(1) features can be added to the program. Metadata is information about the types defined in the program. All. NET assemblies contain a specified set of metadata that describes the types and type members defined in the Assembly. You can add custom features to specify any additional information you need.

(2) one or more features can be applied to the entire assembly, module, or small program elements (such as classes and attributes ).

(3) features can accept parameters in the same way as methods and properties.

(4) The program can use reflection to check its own metadata or metadata in other programs.

 

Ii. Usage features

Features can be placed in almost all declarations (but specific features may be limited to valid declarative types ). In C #, the feature-specific method is to place the feature name enclosed in square brackets above the declaration of the object to which it is applied. It must be placed in front of the applied element and be in the same row as the element.

1 [Serializable] // use the feature SerializableAttribute 2 internal class MyClass 3 {4 [DllImport ("user32.dll")] // use the feature DllImportAttribute 5 private static extern void Do (); 6 7 # multiple features 8 9 private void MethodA ([In] [Out] ref double n) {} 10 private void MethodB ([In, out] ref double n) {} 11 12 # multiple features can be placed on an endregion declaration 13 14 # Some features of region can be specified multiple times for a given entity 15 16 [Conditional ("DEBUG "), conditional ("TEST1")] 17 private void TraceMethod () {} 18 19 # Some features of endregion can be specified multiple times for a given object 20}

[Note] According to the conventions, all feature names end with the word "Attribute" to distinguish them from other items in ". NET Framework. However, when using features in code, you do not need to specify the attribute suffix.

 

3. feature parameters

Many features have parameters, which can be positioning, unnamed, or named parameters. All positioning parameters must be specified in a specific order and cannot be omitted. The naming parameters are optional and can be specified in any order. First, specify the positioning parameter. For example, these three features are equivalent:

1 [DllImport("user32.dll")] 2 [DllImport("user32.dll", SetLastError=false, ExactSpelling=false)] 

The first parameter (DLL name) is the positioning parameter and always appears first. Other parameters are named parameters. In this case, both named parameters are set to false by default, so you can omit them.

 

Iv. features and objectives

The target of a feature is the entity that applies the feature. For example, features can be applied to classes, specific methods, or the entire assembly. By default, a feature is applied to the elements following it. However, you can also explicitly identify whether to apply a feature to a method or its parameters or return values.

To explicitly identify the feature target, Syntax:

[target : attribute-list]

 

Feature Objectives
C # Intended audience
Assembly Entire assembly
Module Current assembly module
Field Fields in a class or structure
Event Event
Method Method orGetAndSetAttribute accessors
Param Method parameter orSetAttribute accessors
Property Attribute
Return Method, attribute indexer, orGetAttribute accessors return values
Type Structure, class, interface, enumeration or delegation

 

// Example: Apply the feature to the assembly and module [assembly: AssemblyTitle ("assembly 4.6.1")] [module: CLSCompliant (true)]
1 // example: Apply features to methods, method parameters, and method return values 2 3 // default: Apply to Method 4 [SomeAttr] 5 int Method1 () {return 0 ;} 6 7 // specify to apply to method 8 [method: SomeAttr] 9 int Method2 () {return 0;} 10 11 // specify to apply to return value 12 [return: someAttr] 13 int Method3 () {return 0 ;}

 

V. Common usage of features

The following lists some common features:

(1) In Web Services, useWebMethodFeature to indicate that the method can be called through the SOAP protocol.

(2) describes how to mail method parameters when interacting with the local code. For more information.

(3) describes the COM attributes of classes, methods, and interfaces.

(4) use the DllImportAttribute class to call unmanaged code.

(5) Describe your Assembly in terms of title, version, description or trademark.

(6) describes the members of the persistent serialization class.

(7) describes how to map class members and XML nodes for XML serialization.

(8) describes the security requirements of the method.

(9) Specify the features used to force security.

(10) The optimization is controlled by the real-time (JIT) compiler to facilitate code debugging.

(11) methods for obtaining information about the caller.

 

6. create custom features

By defining a feature class, you can create your own custom features. This feature class is derived directly or indirectly from Attribute to help you quickly identify the feature definition in metadata.

1 /// <summary> 2 /// role feature 3 /// </summary> 4 /// RoleAttribute: name of the feature, inheriting Attribute, for custom features 5 [AttributeUsage (AttributeTargets. class | AttributeTargets. struct)] 6 public class RoleAttribute: Attribute 7 {8 private string _ name; 9 10 /// <summary> 11 /// enable ID 12 /// </summary> 13 /// IsEnable: name parameter 14 public bool IsEnable {get; set ;} 15 16 /// <summary> 17 /// constructor 18 /// </summary> 19 /// <param name = "name"> </param> 20/ // name: positioning parameter 21 public RoleAttribute (string name) 22 {23 _ name = name; 24} 25}
1 [Role ("Me", IsEnable = true)] // method of calling the feature 2 public class OurClass3 {4 5}

The parameters of the constructor are the positioning parameters of custom features. Any common read/write fields or attributes are named parameters. Note]AttributeUsageFeature. Here it makes the Role feature onlyStructThe statement is valid.

 

1 [AttributeUsage (AttributeTargets. class | AttributeTargets. struct, AllowMultiple = true)] // AllowMultiple: indicates whether the feature 2 public class RoleAttribute: Attribute3 {4 //...... 5}
1 [Role ("You")] // use 2 [Role ("Me", IsEnable = true)] multiple times in the same class 3 public class OurClass4 {5 //...... 6}

Note: If a feature class contains an attribute, the attribute must be a read/write attribute.

 

7. Use reflection access features

Reflection allows you to retrieve information defined by custom features. The main method isGetCustomAttributesIt returns an array of objects, which are equivalent to the source code feature at runtime.

1 /// <summary> 2 /// role feature 3 /// </summary> 4 /// RoleAttribute: name of the feature, inheriting Attribute, for custom features 5 [AttributeUsage (AttributeTargets. class | AttributeTargets. struct)] 6 public class RoleAttribute: Attribute 7 {8 private string _ name; 9 /// <summary> 10 /// enable ID 11 /// </summary> 12 public bool IsEnable {get; set ;} 13 14 /// <summary> 15 /// constructor 16 /// </summary> 17 /// <param name = "name"> </param> 18 public roleAttribute (string name) 19 {20 _ name = name; 21} 22}RoleAttribute. cs
1     [Role("Me", IsEnable = true)]   2     public class OurClass3     {4         //... ...5     }

It is equivalent

1     RoleAttribute role = new RoleAttribute("Me");2     role.IsEnable = true;

However, this code is not executed until OurClass is queried to obtain the feature. Call OurClassGetCustomAttributesA RoleAttribute object is constructed and initialized as described above. If this class has other features, other feature objects are constructed in a similar way. ThenGetCustomAttributesReturns the RoleAttribute object and any other feature object in the array. Then, you can iterate on the array, determine the features applied based on the type of each array element, and extract information from the feature object.

Here, we define a custom feature, apply it to several entities, and retrieve it through reflection.

1 /// <summary> 2 // role features 3 /// </summary> 4 [AttributeUsage (AttributeTargets. class | AttributeTargets. struct, AllowMultiple = true)] 5 public class RoleAttribute: Attribute 6 {7 private readonly string _ name; 8 9 /// <summary> 10 /// enable ID 11 /// </summary> 12 public bool IsEnable {get; set ;} 13 14 /// <summary> 15 /// constructor 16 /// </summary> 17 /// <param name = "name"> </param> 18 public roleAttribute (string name) 19 {20 _ name = name; 21} 22 23 public string GetName () 24 {25 return _ name; 26} 27}
    class MyClass1 { }    [Role("Me")]    class MyClass2 { }    [Role("Me"), Role("You", IsEnable = true)]    class MyClass3 { }
1 class Program 2 {3 static void Main (string [] args) 4 {5 Output (typeof (MyClass1); 6 Output (typeof (MyClass2 )); 7 Output (typeof (MyClass3); 8 9 Console. read (); 10} 11 12 // <summary> 13 // output 14 // </summary> 15 // <param name = "t"> </param> 16 static void Output (Type t) 17 {18 Console. writeLine ($ "Class: {t}"); 19 20 var attributes = t. getCustomAttributes (); 21 foreach (var attribute in attributes) 22 {23 var attr = attribute as RoleAttribute; 24 25 if (attr = null) 26 {27 return; 28} 29 30 Console. writeLine ($ "Name: {attr. getName ()}, IsEnable: {attr. isEnable} "); 31} 32} 33}

 

 

 

 

 

Portal

Just want to briefly describe Expression Tree-Expression Trees

Just want to briefly talk about serialization

 

[Reference] Microsoft official documentation

Related Article

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.