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没有加任何可能会与现有代码冲突的新的关键词

19.1 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的用户,尽管他们不会忍受将来的多种编译器。

 

19.1.1 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:

如果没有泛型,一般数据结构能够使用对象类型去存储任何数据类型。举例,下面所描述的一个很简单的栈的类存储数据在对象数组中。它有两个方法,pushpop,使用对象分别地去接受和返回数据

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:

进一步的关于Stack类的讨论,那么强行将数据的类别加到栈上是不可能的。事实上,一个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<T> 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类。类型参数在类名后面< >分隔符中定义。Stack<T>实例接受它创建和存储的数据类型而不需要转换,这一点远胜于强制的对象转换。直到真正的类型被指定使用之前,类型参数T扮演了一个占位符的角色。注意,T被作为内在数组的元素类型,作为Push的参数和Pop的返回类型。

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

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

public T Pop() {...}
}

When the generic class Stack<T> 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>被使用,替代T的真实类型将被指定。下面的例子里,int 被指定代替T

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

The Stack<int> type is called a constructed type. In the Stack<int> type, every occurrence of T is replaced with the type argument int. When an instance of Stack<int> 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<int> 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<int>类型被称作构造类型.。在Stack<int>里,每次出现T将被类型参数int代替。当一个Stack<int>实例被创建,本身存储items数组是一个int型数组,比非泛型栈的对象数组提供真实性存储效率。同样的,使用PushPop方法操作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<int> is restricted to operate only on int values, so is Stack<Customer> 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<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

Generic type declarations may have any number of type parameters. The Stack<T> 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<T>的例子仅仅只有一个类型参数,但泛型Dictionary类可以含有两个类型参数,一个是关键字的类型,一个是值的类型。

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

public V this[K key] {...}
}

When Dictionary<K,V> is used, two type arguments would have to be supplied:

Dictionary<K,V>使用时,必须提供两种类型参数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值