c#v2.0 擴充特性 翻譯(1)

來源:互聯網
上載者:User
c#v2.0 擴充特性 翻譯(1)

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 介紹幾種語言擴充,泛型,匿名方法,迭代器 和、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.

泛型允許類,結構,介面,代理還有方法被他們儲存和操作資料型別參數化。泛型相當有用,因為他們提供強制的編譯時間類型檢查,要求更少的資料類型之間的顯式轉換,並減少裝箱拆箱的操作和運行時類型檢查。

· 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 features. Following the introduction are four chapters that provide a complete technical specification of the features.

這個章節將介紹這些新特性。隨後的四個章節的介紹將提供有關特性的完整技術規範

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.

c#2.0中的語言擴充最大程度上保證和現有代碼的相容。舉例說,即使c#2.0指定以下詞如yield,partial在特定的上下文有特有的意義,他們依然可以作為標示符。甚至,c#2.0沒有加任何新的可能會在現有代碼衝突的關鍵詞

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.

泛型允許類,結構,介面,代理和方法被他們儲存操作的資料類型參數化。C#泛型將很快被eiffel,ada的使用過泛型的使用者熟悉,或是使用過c++templates,儘管他們不需要忍受以後的多種編譯器。

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:

如果沒有泛型,一般資料結構能使用類型對象去儲存任何資料類型。舉例,下面所描述的一個很簡單的棧的類儲存資料在對象數組中。它有兩個方法push和pop,使用對象分別地去接受和返回資料

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, it 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 tedious to write and carries a performance penalty for run-time type checking:

當使用物件類型的時候棧類的使用更靈活,它並非沒有缺陷。舉例說,它很可能壓入任何類型的值,如一個customer執行個體到一個棧。然而,當一個值返回,pop方法返回的結果必須顯式轉化成適當類型,不但編寫是乏味的並且在運行時的類型檢查降低效能。

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 automatically boxed. When the int is later retrieved, it must be unboxed with an explicit type cast:

如果是一個實值型別,如整型傳入push方法,它自動裝箱。當整型在後來返回的時候,它必須進行顯式的拆箱。

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.

當他們處於動態記憶體分配和運行時類型檢查,裝箱拆箱操作將增加效能消耗。

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:

進一步的關於棧的討論,強迫資料的類別壓入到棧是不可能的。事實上,一個customer執行個體能被壓入棧並且很有可能偶然在它返回時被轉化成錯誤的類型。

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.

以上代碼從技術上說是正確的且在編譯時間是不會報錯的,但對stack類的用法是不正確的。這個問題直到代碼執行才會顯示出來,並拋出InvalidCastException異常.

棧類應當受益於指定元素類型的能力。有了泛型以後,這個將成為可能。

Creating and using generics

建立和使用泛型

Generics provide a facility for creating types that have type parameters. The example below declares a generic Stack class with a type parameter T. The type parameter is specified in < and > delimiters 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 type for the Pop method:

泛型提供了一個便利的方法,通過型別參數去建立類型。下面的例子通過型別參數T聲明了一個泛型的棧。型別參數在類名後面<>分隔字元中定義。Stack執行個體接受它建立和儲存的資料類型而不需要轉換遠勝於強制的對象轉換。

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

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

public T Pop() {...}
}

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

當泛型類Stack被使用,替代T的真實類型將被指定。下面的例子裡,int 被指定代替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 when they’re retrieved.

Stack類型被稱作構造類型. 在Stack裡,每次出現T將被型別參數int代替。當一個Stack執行個體被建立,本身儲存items數組是一個int型數組,比非泛型棧的對象數組提供真實性儲存效率。同樣的,Push和Pop方法操作int 值,如果push其他類型的資料給棧,將導致一個編譯時間錯誤,它排除了當值被返回時所要求的顯式轉化成原型。

Generics provide strong typing, meaning for example that 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:

泛型提供強型別,意味著舉例說來 將一個整型資料壓入Customer 泛類型的棧。正像一個int泛型棧被嚴格約束只能操作int型,因此Customer型被嚴格要求操作Customer對象。下面例子的最後兩行,編譯器編譯的時候會報告錯誤。

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 and one for the type of the values:

泛型聲明可以包括任何數目的型別參數。上面Stack的例子僅僅只有一個型別參數,但泛型Dictionary類可以含有兩個型別參數,一個是關鍵字的類型,一個是值的類型。

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被使用,必須提供兩種型別參數

Dictionary dict = new Dictionary();
dict.Add("Peter", new Customer());
Customer c = dict["Peter"];

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.