c#v2.0 extended feature translation (1)

Source: Internet
Author: User
Tags anonymous data structures integer new features require
Introduction to C # 2.0
C # 2.0 introduces several language extensions, the most important of which, are generics, Anonymous Methods, iterators, and Partial Types.

C#2.0 introduces several language extensions, generics, anonymous methods, iterators, and partial Types.

· Generics permit classes, structs, interfaces, delegates, and methods to is parameterized by the types of data they store a nd manipulate. Generics are useful because they provide stronger compile-time type checking, require fewer explicit conversions between D ATA types, and reduce the need for boxing operations and Run-time type checks.

Generics allow classes, structs, interfaces, proxies, and methods to be parameterized by their storage and manipulation of data types. Generics are useful because they provide mandatory compile-time type checking, require fewer explicit conversions between data types, and reduce the operation of boxed unboxing and run-time type checking.

· Anonymous methods allow code blocks to is written in-line "delegate" where are values expected. Anonymous methods are similar to lambda functions in the Lisp programming language. C # 2.0 supports the creation of "closures" where anonymous methods access surrounding local variables and parameters.

· Iterators are methods that incrementally compute and yield a sequence of values. Iterators make it easy for a type to specify how the foreach statement would iterate over its elements.

· Partial types allow classes, structs, and interfaces to is broken into multiple pieces stored in different source files fo R easier development and maintenance. Additionally, partial types allow separation of machine-generated and user-written parts of types so this it is easier to Augment code generated by a tool.

This chapter gives a introduction to the new features. Following the introduction are four chapters that provide a complete technical of the specification.

This section will introduce these new features. An introduction to the following four chapters will provide a complete technical specification of the characteristics

The language extensions in C # 2.0 were designed to ensure maximum with compatibility code. For example, even though C # 2.0 gives special to the meaning where, words, and yield into partial, these Wo RDS can still be used as identifiers. Indeed, C # 2.0 adds no new keywords as such keywords could conflict with identifiers in existing code.

The language extension in c#2.0 guarantees compatibility with existing code to the greatest extent. For example, even if c#2.0 specifies that the following words, such as yield,partial, have specific meanings in a particular context, they can still be used as identifiers. Even, c#2.0 doesn't add any new keywords that might conflict with existing code

Generics
Generics permit classes, structs, interfaces, delegates, and methods to is parameterized by the types of data they store a nd manipulate. C # generics is immediately familiar to users ' generics in Eiffel or Ada, or to users of C + + templates, though they Do not suffer many of the complications of the latter.

Generics allow classes, structs, interfaces, proxies, and methods to be parameterized by the data types in which they store operations. C # Generics will soon be familiar to Eiffel,ada users, or have used c++templates, although they do not have to endure a variety of subsequent compilers.



Why generics?
Without generics, general purpose data structures can-type object to store data of the any type. For example, the following simple Stack class stores it data in a object array, and its two methods, Push and Pop, use O Bject to accept and return data, respectively:

Without generics, general data structures can use type objects to store any data type. For example, the following describes a very simple stack of classes that store data in an object array. It has two methods for push and pop, using objects to accept and return data separately

public class Stack
{
object[] items;
int count;

public void Push (item) {...}

public Object Pop () {...}
}

While the use of type object makes the Stack class very flexible, it isn't without drawbacks. For example, it's possible to push a value of any type, such a Customer instance, onto a stack. However, when a value was retrieved, the result of the POPs method must explicitly being cast back to the appropriate type, WHI CH is tedious to write and carries a performance penalty for Run-time type checking:

When using object types, the stack class is more flexible to use, and it is not without flaws. For example, it is likely to crush any type of value, such as a customer instance to a stack. However, when a value is returned, the results returned by the Pop method must be explicitly converted to the appropriate type, not only written in a tedious way, but also at Run-time type checking to degrade performance.

Stack stack = new stack ();
Stack. Push (New Customer ());
Customer C = (customer) stack. Pop ();

If a value of a value type, such as an int, are passed to the "Push method", it is automatically boxed. When the ' int is later retrieved, it must to be unboxed with a explicit type cast:

If it is a value type, such as an integer incoming push method, it is boxed automatically. When an integral type is returned later, it must be explicitly disassembled.

Stack stack = new stack ();
Stack. Push (3);
int i = (int) stack. Pop ();

Such Boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time Ty PE checks.

When they are in dynamic memory allocation and Run-time type checking, the boxed unboxing operation increases performance consumption.

A further issue with the Stack class was that it's not-possible to enforce the kind of data placed on a stack. Indeed, a Customer instance can be pushed on a stack and then accidentally cast it to the wrong type after it is retrieved :

Further discussion of the stack, forcing the category of data into the stack is impossible. In fact, a customer instance can be pushed into the stack and is likely to accidentally be converted to the wrong type when it returns.



Stack stack = new stack ();
Stack. Push (New Customer ());
string s = (string) stack. Pop ();

While the code above was a improper use of the Stack class, the code is technically speaking correct and a compile-time er Ror is not reported. The problem does not become apparent until the "code is" executed, at which point a invalidcastexception is thrown.

The Stack class would clearly benefit from the ability to specify its element type. With the generics, that becomes possible.

The code above is technically correct and will not be an error at compile time, but the use of the stack class is incorrect. This problem is not displayed until code execution, and throws a InvalidCastException exception.

Stack classes should benefit from the ability to specify element types. With generics, this will become possible.

Creating and using Generics

Creating and using Generics

Generics provide a facility for creating types of that have type parameters. The example below declares a generic Stack class with a type parameter T. The type parameter is specified at < > delimiters after the class name. Rather than forcing conversions to and from object, instances of Stack accept the "type for which, they are and created e data of that type without conversion. The type parameter T acts as a placeholder until a actual type is specified in use. Note ' T is used as the ' element type for the ' internal items array, the type for the ' parameter to the ' Push method, and T He return type for the Pop method:

Generics provide a convenient way to create types by type parameters. The following example declares a generic stack through the type parameter T. The type parameter is defined after the class name <> separator. The stack instance accepts the data types it creates and stores without the need for conversion much better than forced object conversions.

public class Stack
{
t[] items;
int count;

public void Push (T item) {...}

Public T Pop () {...}
}

When the generic class Stack was used, the actual type to substitute for T is specified. In the following example, the int was given as the type argument for T:

When the generic class stack is used, the true type of the substitution T is specified. In the following example, int is specified instead of T.

Stack stack = new stack ();
Stack. Push (3);
int x = stack. Pop ();

The Stack type is called a constructed type. In the Stack type, every occurrence's T is replaced with the type argument int. When a instance of the Stack is created, the native storage of the items array is a int[] rather than object[], providing SU Bstantial storage efficiency compared to the non-generic Stack. Likewise, the Push and Pop methods of a Stack operate on int values, making it a compile-time error to Push values of othe R types onto the stack, and eliminating the need to explicitly cast values back to their original type when they ' re Retrie Ved.

A stack type is called a constructed type. In stack, each occurrence of T will be replaced by the type parameter int. When a stack instance is created, itself the store items array is an int-type array that provides authenticity storage efficiency over an array of objects that are not generic stacks. Similarly, the push and pop methods manipulate the int value, and if you push other types of data to the stack, it will result in a compile-time error that excludes the explicit conversion to the prototype required when the duty is returned.



Generics provide strong typing, meaning for example ' it is ' an error to push an int onto a stack of Customer objects. Just as a stack is restricted to operate in int values, so are stack restricted to Customer objects, and the compiler 'll errors on the last two lines of the following example:

Generics provide a strong type, which means, for example, pressing an integer data into a stack of the customer's generic type. Just as an int generic stack is tightly constrained to operate only int, the customer is strictly required to manipulate the customer object. The last two lines of the following example report an error when the compiler compiles.

Stack stack = new stack ();
Stack. Push (New Customer ());
Customer C = Stack. Pop ();
Stack. Push (3); Type mismatch error
int x = stack. Pop (); Type mismatch error

Generic type declarations may have any number of type parameters. The Stack example above has only one type parameter, but a generic Dictionary class might have two type parameters, one fo R the type of the keys and one for the values:

A generic declaration can include any number of type parameters. The above stack example has only one type parameter, but the generic dictionary class can contain two type parameters, one is the type of the keyword, and the other is the type of the value.

public class Dictionary
{
public void Add (K key, V value) {...}

Public V this[k key] {...}
}

When Dictionary are used, two type arguments would have to be supplied:

When dictionary is used, two types of parameters must be supplied

Dictionary dict = new Dictionary ();
Dict. ADD ("Peter", New Customer ());
Customer C = dict["Peter"];



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.