C # v2.0 extension characteristics (1)

zhaozj2021-02-16  73

Introduction to C # 2.0 C # 2.0 Introduces Several Language Extensions, The Most Important of Which Are Gnerics, Anonymous Methods, Iterators, And Partial Types.

C # 2.0 Introduce several language extensions, generics, anonymous methods, iterators, and Partial Types.

· Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate. Generics are useful because they provide stronger compile-time type checking, require fewer explicit conversions between data types, and reduce the NEED for boxing operations and run-time Type Checks. generic allows class, structure, interface, and proxy method there is also a way to store and operate data type parameters. The generic is quite useful because they provide a mandatory compile time type check, requires a few different data types, and reduces the installed operation and runtime type check.

· Anonymous methods allow code blocks to be written "in-line" where delegate values ​​are 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 will iterate over its elements. · Partial types allow classes, structs, and interfaces to be broken into multiple pieces stored in different source files for easier development and maintenance. Additionally, partial types allow separation of machine-generated and user-written parts of types so that it is easier to augment code generated by a tool. This chapter gives an introduction to these new Following the Introduction Are Four Chapter That Provide a Complete Technical Specification of the Features.

This chapter will introduce these new features. The introduction of the four chapters will provide a complete technical specification related to characteristics

The language extensions in C # 2.0 were designed to ensure maximum compatibility with existing code. For example, even though C # 2.0 gives special meaning to the words where, yield, and partial in certain contexts, these words 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 the compatibility of existing code. For example, even if C # 2.0 specifies the following words such as Yield, Partial is unique to a specific context, they can still be used as a marker. Even, C # 2.0 does not add any new keywords that may conflict in existing code

Generics Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate. C # generics will be immediately familiar to users of generics in Eiffel or

ADA

, or to users of C Templates, Though They Do Not Suffer Many of The Complications of The Latter.

Pansets allow class, structure, interface, proxy and methods to be parameterized by the data types of their storage operations. The C # generics will be familiar with the use of generic users, or use C Templates, although they don't need to endure a variety of compilers.

Why generics? Without generics, general purpose data structures can use type object to store data of any type. For example, the following simple Stack class stores its data in an object array, and its two methods, Push and Pop, use object to accept And Return Data, Respectively:

If there is no generic, the general data structure can use the type object to store any data type. For example, a simple stack stored in the following is in an object array. It has two methods Push and POP, using objects to accept and return data separately.

Public class stack {object [] Items; int count; public void push (object item) {...} public object pop () {...}} While the use of type object makes the stack class very flexible, IS not without drawbacks. For example, it is possible to push a value of any type, such a Customer instance, onto a stack. However, when a value is retrieved, the result of the Pop method must explicitly be cast back to the appropriate type WHICH IS TEDIOS WRITE AND Carries a Performance Penalty For Run-Time Type Checking: When the object type is used, the use of the stack class is more flexible, it is not a defect. For example, it is likely to press any type of value, such as a Customer instance to a stack. However, when a value returns, the result returned by the POP method must explicitly transform into an appropriate type, not only written is bored and detected in the runtime check to reduce 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, is passed to the push method, IT IS Automatic or Boxed. When the int is latr retrieved, IT Must Be unboxed with an expedition Type Cast:

If it is a value type, such as an integer incoming Push method, it automatically box. When the integer is later returned, it must make an explicit unpacking.

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 type checks.

When they are in dynamic memory allocation and runtime, the packing unpacking operation will increase performance consumption.

A further issue with the Stack class is that it is 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.:

It is impossible to press the category of the stack to force data. In fact, a Customer instance can be pressed into the stack and is likely to be transformed into an error when it returns.

Stack stack = new stack (); stack.push (new customer ()); string s = (String) stack.pop (); while the code Above is an improper use of the stack class, the code is technically speaking correct and a compile-time error is not reported. The problem does not become apparent until the code is executed, at which point an InvalidCastException is thrown. The Stack class would clearly benefit from the ability to specify its element type. With generics, that becomes possible The above code is technically correct and it is incorrect when compiling, but the usage of the Stack class is incorrect. This problem is displayed until the code is executed and the InvalidCastException exception is thrown.

The stack class should benefit from the ability to specify the type of element. This will become possible after a generic.

Creating and using generics

Create and use generics

GENERICS Provide a facility for Creating Types That Have Type Parameters. The Example Below Declares A Generic Stack Class with a Type Parameter IS Specified in

Del

Imiters after the class name. Rather Than Forcing Conversions to and from Object, Instances of Stack

accept the type for which they are created and store data of that type without conversion. The type parameter T acts as a placeholder until an actual type is specified at use. Note that T is used as the element type for the internal items array, the Type for the parameter to the push method, and the return:

The generics provide a convenient way to create types through type parameters. The following example declares a generic stack by the type parameter T. Type parameters are defined in the <> separator after class name. Stack

The instance accepts the type of data it creates and stores without the need to convert the mandatory object conversion.

Public Class Stack

{

T [] items;

INT country;

Public void push (t item) {...} public t pop () {...} }when the generic class stack

IS Used, The Actual Type Substitution for T IS Specified. in The Following Example, Int IS Given As The Type Argument for t:

When generic class stack

The real type of replacement T will be specified. In the example below, 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 OF T IS Replaced with the Type Argument Int. When an Instance of Stack

is created, the native storage of the items array is an int [] rather than object [], providing substantial 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 Other Types Onto The Stack, and Eliminating The NEED To Explicitly Cast Values ​​Back to Their Original Type by're Retrieve.

Stack

Types are called constructive types. In Stack

In addition, T will be replaced by the type parameter INT. When a stack

The instance is created, which is stored in the Items array is an INT type array, providing authenticity storage efficiency than an object array of non-flood stages. Similarly, the PUSH and POP methods operate int values ​​if Push other types of data gives the stack, which will result in a compile time error, which excludes the explicit conversion as required when the value 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 Only On Int Values, So Is Stack

Restricted to Customer Objects, And The Compiler Will Report Errors on The Last Two Lines of The Following Example:

The generic type provides a strong type, meaningful to press a integer data into a Customer Pan-type stack. Just as an INT generic stack is strictly constrained to operate the INT type, so the Customer type is strictly required to operate the Customer object. The last two lines of the following example, the compiler will report an error when compiling.

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 for the Type of The Keys:

The generic statement can include any number of type parameters. The above STACK example only has only one type parameter, but the generic Dictionary class can contain two types of parameters, one is the type of keyword, one is the value of the value.

Public Class Dictionary

{

Public Void Add (K Key, V Value) {...}

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

IS Used, Two Type Arguments Would Have to Be Supplied:

Dictionary

Two types of parameters must be provided

Dictionary

Dict = New Dictionary

();

Dict.Add ("Peter", New Customer ());

Customer C = DICT ["peter"];

转载请注明原文地址:https://www.9cbs.com/read-14099.html

New Post(0)