C #2.0 Introduction

Source: Internet
Author: User

Chapter 1 C #2.0 Introduction
C #2.0 introduces many language extensions. The most important ones are generic, Anonymous Methods, Iterators, and Partial Types ).
• Generics allow classes, structures, interfaces, delegates, and methods to be parameterized by the data types they store and operate on. Generics are useful because they provide more powerful type checks during compilation and require Explicit conversions between fewer data types, in addition, it reduces the need for packing and runtime type checks.
• The anonymous method allows you to write code blocks in "in-line" mode when delegate values are required. The anonymous method is similar to lambda functions in Lisp.
• The iterator can incrementally calculate and generate a series of worthwhile methods. The iterator enables a class to easily explain how the foreach statement iterates each of its elements.
• Incomplete types allow classes, structures, and interfaces to be divided into multiple small blocks and stored in different source files for easy development and maintenance. In addition, incomplete types can be used to separate the code generated by the machine and the part written by the user, which makes it easy to use tools to enhance the generated code.
This chapter first introduces these new features. The introduction is followed by four chapters that provide complete technical specifications for these features.
The Language extension design in C #2.0 ensures high compatibility with existing code. For example, although C #2.0 assigns special meaning to the word where, yield, and partial in a specific environment, these words can still be used as identifiers. Indeed, C #2.0 does not add a keyword that will conflict with the identifier in the existing code.

1.1 generic
Generics allow classes, structures, interfaces, delegates, and methods to be parameterized by the data types they store and operate on. C # generics are very friendly to users who use extensions in the Eifel Or Ada Language and users who use the C ++ template, although they may not be able to tolerate the complexity of the latter.

1.1.1 why is it generic?
No generics. Some common data structures can only store various types of data using the object type. For example, the following simple Stack class stores its data in an object array, and its two methods, Push and Pop, use the object to accept and return data respectively:
Public class Stack
{
Object [] items;
Int count;
Public void Push (object item ){...}
Public object Pop (){...}
}
Although the object type is used to make the Stack class very flexible, it is not a disadvantage. For example, you can press any type of value to the stack, such as a Customer instance. However, when retrieving a value again, you must explicitly convert the value returned by the Pop method to an appropriate type. Writing these conversion changes is tedious to guard against runtime type check errors:
Stack stack = new Stack ();
Stack. Push (new Customer ());
Customer c = (Customer) stack. Pop ();
If a value of the value type, such as int, is passed to the Push method, it is automatically packed. When you retrieve the int value later, you must perform explicit type conversion to unpack it:
Stack stack = new Stack ();
Stack. Push (3 );
Int I = (int) stack. Pop ();
This kind of packing and unpacking operation increases the execution burden, because it brings about dynamic memory allocation and runtime type check.
Another problem with the Stack class is that it is impossible to force the types of data in the Stack. Indeed, a Customer instance can be pushed into the stack, but it will be converted to an incorrect type when retrieved:
Stack stack = new Stack ();
Stack. Push (new Customer ());
String s = (string) stack. Pop ();
Although the above Code is an incorrect use of the Stack class, it is technically correct and will not cause errors during compilation. This error occurs only when the code is run. An InvalidCastException is thrown.
The Stack class will undoubtedly benefit from its ability to limit its element types. Using Generics makes it possible.

1.1.2 create and use generic
Generics provide a technique to create a type with type parameters. The following example declares a generic Stack class with type parameter T. The delimiters "<" and ">" after the type parameter and class name are specified. The <T> instance created by a Stack of a certain type can accept the data of this type without any conversion, which is too strong to replace with the object. Type parameter T acts as a placeholder until an actual type is specified during use. Note that T is equivalent to the Data Type of the internal array, the parameter type accepted by the Push method, and the return value type of the Pop method:
Public class Stack <T>
{
T [] items;
Int count;
Public void Push (T item ){...}
Public T Pop (){...}
}
When using a generic Stack <T>, you must specify the actual type to replace T. In the following example, int is specified as the parameter type T:
Stack <int> stack = new Stack <int> ();
Stack. Push (3 );
Int x = stack. Pop ();
The Stack <int> type is called the constructed type ). All T values in the <int> type of the Stack are replaced with the type parameter int. When a Stack <int> instance is created, the local storage of the items array is int [] rather than object [], which provides a substantial storage, it is more efficient than non-generic Stack. Similarly, the Push and Pop methods in the Stack <int> only operate on int values. If you press other types of values into the Stack, errors during compilation will be obtained, when retrieving a value, it cannot be displayed as the original type.
A wildcard can provide a strong type, which means that, for example, pushing an int to the stack of a Customer object will produce an error. This is because Stack <int> can only operate on int values, while Stack <Customer> can only operate on Customer objects. The last two lines in the following example cause the compiler to report an error:
Stack <Customer> stack = new Stack <Customer> ();
Stack. Push (new Customer ());
Customer c = stack. Pop ();
Stack. Push (3); // Type Mismatch Error
Int x = stack. Pop (); // Type Mismatch Error
The generic type declaration allows any number of type parameters. In the preceding Stack <T> example, there is only one type parameter, but a generic Dictionary class may have two types of parameters, one is the key type and the other is the value type:
Public class Dictionary <K, V>
{
Public void Add (K key, V value ){...}
Public V this [K key] {...}
}
When using Dictionary <K, V>, you must provide two types of parameters:
Dictionary <string, Customer> dict = new Dictionary <string, Customer> ();
Dict. Add ("Peter", new Customer ());
Customer c = dict ["Peter"];

1.1.3 generic type instantiation
Similar to non-generic types, compiled generic types are also represented by Intermediate Language (IL, Intermediate Language) commands and metadata. The IL of the generic type is encoded by the type parameter.
When a program creates a constructed generic type instance for the first time, such as Stack <int> ,. NET instant Compiler (JIT, just-in-time) in the public language runtime converts generic IL and metadata into local code, and replaces type parameters with actual types in the process. The reference to the constructed generic type follows the same local code. The process of creating a specific construction type from the generic type is called the generic type instantiation ).
. NET public language runtime creates a special copy for each generic type instantiated by the type, and all the reference types share a separate copy (because, at the local code level, reference knowledge has pointers of the same performance ).

1.1.4 Constraints
Generally, a generic class does not store data based on a certain type of parameters, but also calls methods for a given type of objects. For example, the Add method in Dictionary <K, V> may need to use the CompareTo method to compare the key values:
Public class Dictionary <K, V>
{
Public void Add (K key, V value)
{
...
If (key. CompareTo (x) <0) {...} // error, no CompareTo Method
...
}
}
Because the specified type parameter K can be of any type, it can be assumed that the existing parameter key has only members from the object, such as Equals, GetHashCode, and ToString; therefore, a compilation error occurs in the preceding example. Of course, you can convert the parameter key to a CompareTo method type. For example, the parameter key can be converted to IComparable:
Public class Dictionary <K, V>
{
Public void Add (K key, V value)
{
...
If (IComparable) key). CompareTo (x) <0 ){...}
...
}
}
When this scheme works, it will cause dynamic type conversion at runtime, which will increase the overhead. Even worse, it may also delay the error report to runtime. If a key does not implement the IComparable interface, an InvalidCastException is thrown.
To provide more powerful type checking during compilation and reduce type conversion, C # allows an optional constraints List for each type parameter. The constraints of a type parameter specify the requirements that a type must comply with, so that this type parameter can be used as a variable. The constraint is declared by the keyword where, followed by the name of the type parameter, followed by a list of classes or interface types, or the constructor constraint new ().
To enable the Dictionary <K, V> class to ensure that the key value always implements the IComparable interface, the class declaration should specify a constraint for the type parameter K:
Public class Dictionary <K, V> where K: IComparable
{
Public void Add (K key, V value)
{
...
If (key. CompareTo (x) <0 ){...}
...
}
}
With this declaration, the compiler can ensure that all types provided to the type parameter K implement the IComparable interface. Furthermore, you do not need to explicitly convert a key value to an IComparable interface before calling the CompareTo method. All members of a value of the constrained type parameter type can directly use it.
For a given type parameter, you can specify any number of interfaces as constraints, but you can only specify one class (as constraints ). Each constrained type parameter has an independent where clause. In the following example, type parameter K has two interface constraints, and type parameter E has a class constraint and a constructor constraint:
Public class EntityTable <K, E>
Where K: IComparable <K>, IPersistable
Where E: Entity, new ()
{
Public void Add (K key, E entity)
{
...
If (key. CompareTo (x) <0 ){...}
...
}
}
The constructor constraint in the preceding example, new (), ensures that the type of the E-type variable has a common, no-argument constructor, and allows generic classes to use new E () to create an instance of this type.
Be careful when using the type parameter constraints. Although they provide more powerful type checks during compilation and improve performance in some cases, they still limit the use of generic types. For example, a generic List <T> may constrain T to implement the IComparable interface so that the Sort method can compare the elements. However, in this case, List <T> cannot be used for those types that do not implement the IComparable interface, even though the Sort method has never been actually called in this case.

1.1.5 generic Method
Sometimes a type parameter is not required by the entire class, but only used in a specific method. Generally, this occurs when you create a method that requires a generic type as a parameter. For example, when using the Stack <T> class described earlier, a common mode is to input multiple values in one row, it is very convenient to write a method to complete this work by calling its class separately. For a specific constructed type, such as Stack <int>, this method looks like this:
Void PushMultiple (Stack <int> stack, params int [] values ){
Foreach (int value in values) stack. Push (value );
}
This method can be used to press multiple int values into one Stack <int>:
Stack <int> stack = new Stack <int> ();
PushMultiple (stack, 1, 2, 3, 4 );
However, the above method can only work on a specific constructed type Stack <int>. To make him work on any Stack <T>, this method must be written as a generic method ). A generic method has one or more type parameters, which are specified by the "<" and ">" delimiters after the method name. This type of parameter can be used in the parameter list, return to, and method body. A generic PushMultiple method looks like this:
Void PushMultiple <T> (Stack <T> stack, params T [] values ){
Foreach (T value in values) stack. Push (value );
}
With this method, you can press multiple elements into any Stack <T>. When calling a generic method, type parameters should be placed in angle brackets in the function call. For example:
Stack <int> stack = new Stack <int> ();
PushMultiple <int> (stack, 1, 2, 3, 4 );
This generic PushMultiple method is more reusable than the previous version because it can work on any Stack <T>, but it does not seem comfortable because it must provide a type parameter for T. However, many times the compiler can infer the correct type parameter by passing other parameters to the method. This process is called type inferencing ). In the preceding example, because the first formal parameter type is Stack <int> and all subsequent parameter types are int, the compiler can determine that the type parameter must be int. Therefore, you do not need to provide the type parameter when calling the generic PushMultiple method:
Stack <int> stack = new Stack <int> ();
PushMultiple (stack, 1, 2, 3, 4 );

1.2 anonymous method
Practice and other callback methods usually need to be called through a special delegate, rather than directly calling. Therefore, so far, we can only put a code for practical processing and callback in a specific method, and then explicitly create a delegate for it. Instead, the anonymous method allows the code "in-line" associated with a delegate to the place where the delegate is used, we can easily write the code directly in the delegated instance. In addition to being comfortable, the anonymous method also shares access to function members contained in local statements. If you want to achieve this type of sharing in the naming method (different from the anonymous method), you need to manually create a helper class and "upgrade (lifting)" The local member to the class domain.
The following example shows how to obtain a simple input from a form that contains a list box, a text box, and a button. When the button is pressed, the text in the text box is added to the list box.
Class InputForm: Form
{
ListBox listBox;
TextBox textBox;
Button addButton;
Public MyForm (){
ListBox = new ListBox (...);
TextBox = new TextBox (...);
AddButton = new Button (...);
AddButton. Click + = new EventHandler (AddClick );
}
Void AddClick (object sender, EventArgs e ){
ListBox. Items. Add (textBox. Text );
}
}
Although there is only one statement in the response to the button Click event, this statement must also be placed in an independent method with a complete parameter list, and you must manually create the EventHandler delegate that references this method. With the anonymous method, the code for event processing becomes more concise:
Class InputForm: Form
{
ListBox listBox;
TextBox textBox;
Button addButton;
Public MyForm (){
ListBox = new ListBox (...);
TextBox = new TextBox (...);
AddButton = new Button (...);
AddButton. Click + = delegate {
ListBox. Items. Add (textBox. Text );
};
}
}
An anonymous method consists of the keyword delegate and an optional parameter list, and puts the statement into the "{" and "}" qualifiers. The anonymous method in the preceding example does not use the parameters provided to the delegate. Therefore, the parameter list can be omitted. To access parameters, your name and method should contain a list of parameters:
AddButton. Click + = delegate (object sender, EventArgs e ){
MessageBox. Show (Button) sender). Text );
};
In the preceding example, an implicit conversion occurs between the anonymous method and the EventHandler delegate type (the type of the Click event. This implicit conversion is feasible because the parameter list and return value types of this delegate are compatible with anonymous methods. The exact compatibility rules are as follows:
• If one of the following statements is true, the delegated parameter list is compatible with the anonymous method:
O The anonymous method does not have a parameter list and the delegate does not have an output (out) parameter.
O The parameter list of the anonymous method precisely matches the number, type, and modifier with the delegate parameter.
• If one of the following statements is true, the delegate return value is compatible with the anonymous method:
O the return value type of the delegate is void, and the anonymous method does not have a return statement or its return statement does not contain any expressions.
O the return value type of the delegate is not void, but the value of the expression associated with the return statement of the anonymous method can be explicitly converted to the return value type of the delegate.
Only when the parameter list and return value types are compatible can an anonymous type be implicitly converted to the delegate type.
The following example uses the anonymous method to "inline (in-lian)" the function )". The anonymous method is passed as a Function delegate type.
Using System;
Delegate double Function (double x );
Class Test
{
Static double [] Apply (double [] a, Function f ){
Double [] result = new double [a. Length];
For (int I = 0; I <a. Length; I ++) result [I] = f (a [I]);
Return result;
}
Static double [] MultiplyAllBy (double [] a, double factor ){
Return Apply (a, delegate (double x) {return x * factor ;});
}
Static void Main (){
Double [] a = {0.0, 0.5, 1.0 };
Double [] squares = Apply (a, delegate (double x) {return x * x ;});
Double [] doubles = MultiplyAllBy (a, 2.0 );
}
}
The Apply method requires a given Function that accepts the double [] element and returns the double [] as the result. In the Main method, the second parameter passed to the Apply method is an anonymous method, which is compatible with the Function delegate type. This anonymous method only returns the square value of each element. Therefore, the double [] obtained by calling the Apply method contains the square value of each value in.
The MultiplyAllBy method creates a double [] by multiplying each value in the parameter array by a given factor and returns the result. To generate this result, the MultiplyAllBy method calls the Apply method and passes it an anonymous method that can multiply the x parameter and the factor.
If the scope of a local variable or parameter includes an anonymous method, the variable or parameter is called an external variable (outer variables) of the anonymous method ). In the MultiplyAllBy method, a and factor are the external variables passed to the anonymous method of the Apply method. Generally, the lifetime of a local variable is restricted within the block or associated statement. However, the lifetime of a captured external variable needs to be extended to at least when the delegate reference to the anonymous method meets the garbage collection condition.

1.2.1 method group Conversion
As described in the previous section, an anonymous method can be implicitly converted to a compatible delegate type. C #2.0 allows the same conversion for a group of methods, that is, the explicit instantiation of a delegate can be omitted at any time. For example, the following statement:
AddButton. Click + = new EventHandler (AddClick );
Apply (a, new Function (Math. Sin ));
You can also write:
AddButton. Click + = AddClick;
Apply (a, Math. Sin );
When short form is used, the compiler can automatically infer which delegate type should be instantiated, but the effect is the same as that of long form.

1.3 iterator
The foreach statement in C # is used to iterate the elements in an enumerable set. To implement enumerable functions, a set must have a GetEnumerator method with no parameters and an enumerator. Generally, enumerators are difficult to implement. Therefore, it is important to simplify the tasks of enumerators.
Iterator is a statement block that generates an ordered sequence of (yields) values. The iterator distinguishes one or more yield statements from other statement blocks:
• The yield return Statement generates the next value of this iteration.
• The yield break statement indicates that this iteration is complete.
As long as the return value of a function member is an enumerator interfaces or enumerable interfaces, we can use the iterator:
• The so-called enumerator is an excuse for System. Collections. IEnumerator and a type constructed from System. Collections. Generic. IEnumerator <T>.
• The enumerated interface refers to the System. Collections. IEnumerable and constructed from System. Collections. Generic. IEnumerable <T>.
It is important to understand that an iterator is not a member, but a function member. A member implemented by the iterator can be overwritten or overwritten by one or more members that use or do not use the iterator.
The following Stack <T> class uses the iterator to implement its GetEnumerator method. The iterator enumerates the elements in the stack in the order from the top to the end.
Using System. Collections. Generic;
Public class Stack <T>: IEnumerable <T>
{
T [] items;
Int count;
Public void Push (T data ){...}
Public T Pop (){...}
Public IEnumerator <T> GetEnumerator (){
For (int I = count-1; I> = 0; -- I ){
Yield return items [I];
}
}
}
The GetEnumerator method makes the Stack <T> An Enumeration type, which allows the instance of the Stack <T> to use the foreach statement. In the following example, values 0 to 9 are pushed into an integer stack, and each value is displayed in the order from the top to the end using the foreach loop.
Using System;
Class Test
{
Static void Main (){
Stack <int> stack = new Stack <int> ();
For (int I = 0; I <10; I ++) stack. Push (I );
Foreach (int I in stack) Console. Write ("{0}", I );
Console. WriteLine ();
}
}
The output in this example is:
9 8 7 6 5 4 3 2 1 0
The statement implicitly calls the GetEnumerator method without parameters of the set to obtain an enumerator. Only one GetEnumerator method without parameters can be defined in a collection class. However, there are many ways to implement enumeration, including using parameters to control enumeration. In these cases, an iterator can be used to return the attributes and methods of the enumerated interface. For example, Stack <T> can introduce two new attributes: IEnumerable <T> TopToBottom and BottomToTop:
Using System. Collections. Generic;
Public class Stack <T>: IEnumerable <T>
{
T [] items;
Int count;
Public void Push (T data ){...}
Public T Pop (){...}
Public IEnumerator <T> GetEnumerator (){
For (int I = count-1; I> = 0; -- I ){
Yield return items [I];
}
}
Public IEnumerable <T> TopToBottom {
Get {
Return this;
}
}
Public IEnumerable <T> BottomToTop {
Get {
For (int I = 0; I <count; I ++ ){
Yield return items [I];
}
}
}
}
The get accessor of the TopToBottom attribute only returns this, because the stack itself is an enumerable type. The BottomToTop attribute uses the C # iterator to return an enumeration interface. The following example shows how to use these two attributes to enumerate the elements in the stack in any order:
Using System;
Class Test
{
Static void Main (){
Stack <int> stack = new Stack <int> ();
For (int I = 0; I <10; I ++) stack. Push (I );
Foreach (int I in stack. TopToBottom) Console. Write ("{0}", I );
Console. WriteLine ();
Foreach (int I in stack. BottomToTop) Console. Write ("{0}", I );
Console. WriteLine ();
}
}
Of course, these attributes can also be used outside the foreach statement. The following example passes the result of calling the property to an independent Print method. This example also shows the method body used by an iterator as a FromToBy method with parameters:
Using System;
Using System. Collections. Generic;
Class Test
{
Static void Print (IEnumerable <int> collection ){
Foreach (int I in collection) Console. Write ("{0}", I );
Console. WriteLine ();
}
Static IEnumerable <int> FromToBy (int from, int to, int ){
For (int I = from; I <= to; I + = ){
Yield return I;
}
}
Static void Main (){
Stack <int> stack = new Stack <int> ();
For (int I = 0; I <10; I ++) stack. Push (I );
Print (stack. TopToBottom );
Print (stack. BottomToTop );
Print (FromToBy (10, 20, 2 ));
}
}
The output in this example is:
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
10 12 14 16 18 20
The generic and non-generic enumerated interfaces have only one independent Member, and the GetEnumerator method without parameters returns an enumeration interface. An enumerator factory is similar to an enumerator factory ). Each time you call the GetEnumerator method of a class that correctly implements the enumeration interface, an independent enumerator is generated.
Using System;
Using System. Collections. Generic;
Class Test
{
Static IEnumerable <int> FromTo (int from, int ){
While (from <= to) yield return from ++;
}
Static void Main (){
IEnumerable <int> e = FromTo (1, 10 );
Foreach (int x in e ){
Foreach (int y in e ){
Console. Write ("{0, 3}", x * y );
}
Console. WriteLine ();
}
}
}
The code above prints a simple multiplication table from 1 to 10. Note that the FromTo method is called only once to generate enumeration interface e. E. GetEnumerator () is called multiple times (using the foreach statement) to generate multiple identical enumerators. These enumerators encapsulate the code specified in the FromTo declaration. Note that the from parameter is changed during iteration. However, the enumerator is independent, because for the from parameter and to parameter, each enumerator has its own copy. When you implement an enumerative class or an enumerator class, the transition between the enumerators (an unstable state) is one of the many subtle flaws that must be eliminated. The design of the iterator in C # can help eliminate these problems and implement robust enumeration classes and enumerators classes in a simple and instinctive way.

1.4 incomplete type
Although maintaining all types of code in a single file is a good programming practice, sometimes when a class becomes very large, this becomes an unrealistic constraint. In addition, programmers often use the code generator to generate an initial structure of an application and then modify the generated code. Unfortunately, when the original code needs to be released again in the future, the existing corrections will be overwritten.
Incomplete types allow classes, structures, and interfaces to be divided into multiple small blocks and stored in different source files for easy development and maintenance. In addition, incomplete types can be used to separate the code generated by the machine and the part written by the user, which makes it easy to use tools to enhance the generated code.
To define a type in multiple parts, we use a new modifier -- partial. The following example implements an incomplete class in two parts. These two parts may be in different source files. For example, the first part may be generated by the machine through the database shadow tool, and the second part is manually created:
Public partial class Customer
{
Private int id;
Private string name;
Private string address;
Private List <Order> orders;
Public Customer (){
...
}
}
Public partial class Customer
{
Public void SubmitOrder (Order order ){
Orders. Add (order );
}
Public bool HasOutstandingOrders (){
Return orders. Count> 0;
}
}
When the two parts are compiled together, the generated code is as if this class was written in a unit:
Public class Customer
{
Private int id;
Private string name;
Private string address;
Private List <Order> orders;
Public Customer (){
...
}
Public void SubmitOrder (Order order ){
Orders. Add (order );
}
Public bool HasOutstandingOrders (){
Return orders. Count> 0;
}
}
All parts of incomplete types must be compiled together before they can be merged during compilation. Note that incomplete types do not allow extension of compiled types.

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.