[CLR via C #] 10. Attributes

Source: Internet
Author: User

I. No parameter Property

We strongly recommend that you set all fields to private. If the user or type is allowed to obtain or set the status information, a method for this purpose is published. The method that encapsulates field access is usually called the accessor method. The accessor method can check the rationality of the data to ensure that the object state is never damaged. The following code:

       =  (value <=   ArgumentOutOfRangeException(, =

CLR provides a Property mechanism, which mitigates the impact of the first drawback. Colleagues completely eliminate the second drawback. The following code is used:
      {  { m_Name = value; }  {  (value <= )                          ArgumentOutOfRangeException(, =

  Employee emp = = = , emp.Name, emp.Age);

Each attribute has a name and a type (the type cannot be void). The attribute cannot be overloaded. That is to say, attributes with the same name and different types cannot be defined. When defining an attribute, the compiler generates the following two or three items in the final hosting program: *) a method that represents the get accesser method of the attribute. Generated only when the get accessors method is defined in the property. *) Represents a method of the set accessor method of the attribute. Generated only when the set accessors method is defined in the property. *) An attribute definition in the managed Assembly metadata. This item must be generated. As an example, the compiler generates four method definitions. Or the compiler will append the get _ or set _ prefix before the attribute name you specify to automatically generate the names of these methods. C # built-in support for attributes. When the compiler finds that the Code tries to obtain or set an attribute, it actually generates a call to the preceding method. 1. if you only create an attribute to encapsulate a private field, C # also provides a simpler syntax called Automatically implemented attribute (AIP ). The following is an example of the Name attribute:
               String Name {;

1) attributes can be read-only or write-only, and field access is always readable and writable. If you define an attribute, it is best to provide it with get and set accessors methods at the same time. 2) an attribute method may throw an exception. Field access will never throw an exception. 3) The attribute cannot be passed to the method as an out or ref parameter, but the field can. 4) attribute methods may take a long time to execute; field access is always completed immediately. 5) if the attribute method is called multiple times in a row, a different value may be returned each time, and the same value will be returned for each field call. 6) attribute methods may cause obvious side effect (in addition to setting or obtaining properties, the object state may change); field access will never. 7) the attribute method may require additional memory or return an incorrect reference pointing to something that is not part of the object state. In this way, the modification to the returned object does not work on the original object. On the contrary, a query field always returns a correct reference, and it points to something that is always part of the original object state. Currently, developers have never been inferior to attribute dependencies, and there is often no need to use attributes. After a closer look at the comparison above, you will find that in rare cases, to define attributes. The only benefit of a property is that it provides a simplified syntax. Compared with calling a common method, the property not only improves the code performance, but also hinders the understanding of the Code. It is recommended that developers write the Getxxx and Setxxx Methods honestly. We hope the compiler provides a special, simplified syntax that is different from the field access syntax, developers know that they are actually calling a method. 3. We often need to construct an object and set some common attributes (or fields) of the object ). To simplify this common programming mode, C # supports a special object initialization syntax. For example, [()] indicates.
Employee e =  Employee[()] { Name = , Age =  }
The real benefit of object initializer syntax is that it allows encoding in the expression context (relative to the statement context) and allows the combination of multiple functions, thus enhancing the readability of the Code. So we can write the following:
 s =  Employee() {Name = , Age = }.ToString().ToUpper();
4. Using the C # anonymous type, the anonymous type can be declared using a very concise syntax. The Tuple type is a type that contains a set of attributes, which are usually associated in some way.
 o1 =  { Name = , Year = , o1.Name, o1.Year);

The first line of code creates an anonymous type without specifying a type name after the new Keyword. Therefore, the compiler automatically creates a type name for me, it does not tell me what the name is (this is the origin of the word anonymous type), but the compiler knows. Although I don't know what type the variable o1 declares, I can use the "implicit inference type local variable" function (var) of C ).

The compiler supports the use of two other syntaxes to declare attributes of the anonymous type. It deduce the attribute name and type based on the variables:

String Name = = o2 =  { Name, dt.Year };

In this example, the compiler determines that the first attribute is named Name. Because Name is the Name of a local variable, the compiler sets the attribute type to the same type as the local variable: String. For the second attribute, the compiler uses the name of the field/attribute: Year. Year is an Int32 attribute of the DateTime class, so the Year attribute of the anonymous type is also an Int32.

If the compiler sees that you have defined Multiple anonymous types in the source code and these types have the same structure, it will only create one anonymous type definition, however, you can create multiple instances of this type. The same structure means that each attribute of these anonymous types has the same type and name, and the specified order of these attributes is the same. The anonymous type is often used in combination with the LINQ technology. You can use LINQ to query and generate a set of objects. These objects are of the same anonymous type. Then, you can process the objects in the result set. All of these are done in one method. 5. The System. Tuple type is in the System namespace. Microsoft defines several generic Tuple (tuples) types. All of them are derived from objects. The difference is only the number of elements (number of generic parameters ). In computer programming, the number of elements of a function or operation is the number of real parameters or operands obtained by the function.
  Tuple<T1> Tuple(T1 item1) { m_Item1 = item1 { 

 

The programming language also supports the so-called parameter attributes. Its get accessors method receives one or more attributes, and the set accessors method receives two or more parameters. C # Use the array-style syntax to publish the attributes of parameters (Indexer ). In other words, you can regard the indexer as a way for C # developers to reload the [] operator. The following is an instance BitArray class, which allows an array-style syntax to index a group of binary bits maintained by an instance of this class.
                   (numBits <=   ArgumentOutOfRangeException(        m_numBits =        m_byteArray =  Byte[(m_numBits + ) /      Boolean                      ((bitPos < ) || (bitPos >=  ArgumentOutOfRangeException(,  +             ((m_byteArray[bitPos / ] & ( << (bitPos % ))) !=          ((bitPos < ) || (bitPos >=  ArgumentOutOfRangeException(,  +                m_byteArray[bitPos / ] =/ ] | ( << (bitPos %                 m_byteArray[bitPos / ] =/ ] & ~( << (bitPos % 

  
          BitArray ba =  BitArray(         (Int32 x = ; x < ; x++= (x %  ==          (Int32 x = ; x < ; x++ + x +  + (ba[x] ?  : 

 

CLR does not distinguish between the parameter-free attributes and the parameter attributes. For CLR, each attribute is only a pair of methods and metadata defined in the type. Set this [...] as the syntax for expressing an indexer, this is purely the choice of the C # team. For this reason, C # Only Allows defining the indexer on the object instance,

For simple get and set accessors, the JIT compiler will inline the code. In this way, the use of attributes (rather than fields) will have no performance loss. Inline refers to directly compiling the code of a method into its method. This avoids the overhead of calling during runtime, at the cost that the code of the compiled method will become larger. Attribute accessors usually only contain a small amount of code, so inline operations will make the locally generated code smaller and faster to execute. The JIT compiler does not inline attributes when debugging code, as this makes debugging difficult.

 

Sometimes we want to specify an accessibility for the get accessor method and another accessibility for the set accessor method. As follows:

  {   { m_name =

When defining an attribute, if the two accessors need to have different accessibility, the C # syntax requires that the attribute itself be specified with the least restrictive access. Then, you can select only one of the two accessors to apply the accessibility that is highly restricted. In the preceding example, the attribute is declared as public, and the set accessors method is declared as protected (the limit is greater than public ).

 

Since attributes are essentially methods, and C # And CLR allow methods to be generic, C # does not allow defining generic attributes. This cannot be understood in terms of concept. Attribute indicates an object feature that can be queried or set. In terms of concept, attributes do not have behaviors.

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.