. NET, special type members in

Source: Internet
Author: User
Tags abstract definition constructor require
. NET, special type members in

----Microsoft. NET Platform series of articles three

Translation/Zhao Ning

In the previous two articles, we studied the basics of types. In this article we will examine certain special members of type definition. These types contribute to object-oriented design in a way that greatly simplifies the syntax required to handle types and their object instances.

Type Builder
You're already familiar with what is a constructor, which is responsible for initializing the state of an object instance. In addition to the instance Builder, Microsoft (R). NET Common language runtime (CLR) also supports type constructors (also known as static constructors, class constructors, or type initialization). The type Builder can be applied to interfaces, classes, and numeric types. It allows you to implement the necessary initialization before any member declared in the type is accessed. The type builder does not require arguments and always returns a void type. The type builder accesses only static fields of a type and its usual purpose is to initialize the fields. Before any instance of a type is created and any static fields or methods of the type are referenced, you must ensure that the type Builder is already running.
Many languages, including C #, automatically generate type constructors when defining types. However, some languages require an explicit (manual) implementation of the Type Builder.
To understand the type builder, let's look at the types that are defined in C #:

Class Atype {
static int x = 5;
}

When this code is created, the compiler automatically generates the Atype type Builder. This constructor is responsible for initializing the static field x to the value 5. If you use ILDASM, it's easy to recognize the type constructor method, because their names are all. cctor (for class constructors).
In C #, you can implement the type Builder yourself by defining the static constructor method in the type. The use of the keyword static means that this is the type constructor, not the instance builder. Here is a very simple example:

Class Atype {
static int x;

Static Atype () {
x = 5;
}
}

This type definition is the same as the previous one. Note the Type builder must not attempt to create its own type instance, and the constructor cannot reference non-static members of the type.
Finally, if you compile the following code with the C # compiler, it produces a separate type builder method:

Class Atype {
static int x = 5;

Static Atype () {
x = 10;
}
}

The constructor initializes the x=5 first, and then initializes the x=10. In other words, the result type builder produced by the compiler first contains the initialization code for the static field, followed by the code for the type constructor.

Property
Many type-defined properties can be either re-obtained or modified. These properties are often implemented with Type field members. For example, the following is a type definition that contains two fields:

Class Employee {
Public String Name;
Public Int32 age;
}

If you create an instance of this type, you can easily get or set the property with the following code:

Employee E = new Employee ();
E.name = "Jeffrey Richter"; Set name Properties
E.age = 36; Setting Age Properties

Console.WriteLine (E.name); Show "Jeffrey Richter"

Using attributes in this way is very common. But from my point of view, the above code will not be implemented as listed. One of the covenants in object-oriented design and programming is data abstraction. It means that the type field cannot be exposed as a public field because it is too easily modified to allow people to write code that improperly uses the field, thereby destroying the object's state. For example, it is easy for someone to write the following code to destroy an employee object:

E.age =-5; How can a person's age be-5?

So, when designing types, I strongly recommend that all fields be private (private) or at least protected (protected)--never public. Then, let the person who uses the type be able to get or set properties, specifically to provide a method for this. The way to package access to a field is called an accessor (or accessor method) method. These methods are capable of achieving integrity checks at any time and ensuring that the object's state is not compromised. For example, I rewrote the employee class that I defined earlier, as shown in Figure I. While this is a simple example, you can understand the great benefits of abstract data fields, and you can learn how to easily read-only properties, or simply not implement an accessor method to easily achieve a write-only property.
The data abstraction method shown in figure I has two drawbacks. First, because you want to implement additional functions, you need to write more code. Second, the consumer of the type must now invoke the method instead of just referring to a single field name:

E.setage (36); Updates The Age
E.setage (-5); Throws an exception

I think that all of us would agree that these shortcomings are trivial compared to their merits, but the runtime still provides a mechanism of attributes that makes the first disadvantage bearable and eliminates the second disadvantage altogether.
The classes in Figure II use properties that are the same as those shown in figure one. As you can see, the attribute simplifies some code, but more importantly allows you to write your own code as follows:

. Age = 36; Update age
E.age =-5; Throw abnormal throws an exception

The return value of the Get property accessor is the same as that passed to the set property accessor parameter value type. The return value of the set property accessor is void and the Get property accessor has no entry parameters. Attributes can be static, virtual, abstract, internal, private, protected, or public. In addition, properties can be defined in the interface, which is discussed later.
I should also point out that properties do not have to be associated with fields. For example, type System.IO.FileStream defines a length property that returns the number of bytes in the stream. When the Get method of the length property is called, the length is not provided by the field, but instead the other function is called to request the underlying operating system to return the number of bytes of the open file stream.
When you create a property, the compiler actually emits a special get_proname and/or Set_proname accessor method (here Proname is the property name). Most compilers understand these proprietary methods and allow developers to access these methods with specialized attribute syntax. However, compilers that adhere to the common language runtime specification do not need to fully support properties, as long as the private accessor method calls are supported.
In addition, for compilers that fully support properties, the syntax used to define and use attributes is slightly different, such as C + + with Managed Extensions requiring the use of the _property keyword.

Indexed properties
Some types, such as System.Collections.SortedList, expose a list of logical elements. In order to easily access elements in this type, you can define an index property (also called an indexer-indexer). Figure three shows an example of an indexed property, and its indexer is extremely simple to use:

BitArray ba = new BitArray (14);
for (int x = 0; x <% x + +) {
Set all even digits to "on"
BA[X] = (x% 2 = 0);
Console.WriteLine ("Bit" + x + "is" + (Ba[x]?) On ': Off '));
}

In the BitArray example in Figure three, the indexer takes a Int32 parameter: bitposition. The indexer must have at least one parameter, and the number of arguments can be two or more. These parameters (and the return type) can be of any type. It is very common to create an indexer with string as a parameter to find values in a federated array. A type can provide multiple indexers, as long as their prototypes are different.
Like the Set property, the Set indexer access method contains a hidden parameter, a value that represents a new value when the accessor method is invoked. BitArray's set access method shows the use of this parameter value.

A well-designed indexer should have get and set two accessor methods. Even if you can only implement get access methods (for read-only semantics) or implement only set access methods (for write-only semantics), it is recommended that your indexer implement two accessors. The reason is simple, the user of the index does not want only half of the behavior. For example, when you write the following two lines of code, the consumer does not want to see a compiler error:
String s = someobj[5]; If there are accessors, compile OK
SOMEOBJ[5] = s; If there is no accessor, compilation error

Indexers always act as instances of a type and cannot be declared static. But it can be public, private, protected, or internal.
When you create an indexed property, the compiler actually publishes a dedicated get_item and/or set_item accessor method. Most compilers will understand these specialized methods and will allow developers to access these methods using specialized indexed attribute syntax. However, compilers that are compatible with the CLS (Common Language System) do not need to fully support indexed properties, as long as the compiler supports private accessor calls.
Similarly, the syntax required to define and use these properties is slightly different for compilers that fully support indexed properties. For example, C + + Managed Extensions require the use of the _property keyword.

Conclusion
The concepts discussed in this article are for all. NET programmer is extremely important. The special type members I mentioned make the component the most important part of the common language runtime. In other words, modern components are designed to support attributes.
In the next article I'll introduce delegates and event members because they are integral to the development and design of component-based applications.




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.