19.C#2.0 Introduction
C#2.0 introduces several language extensions, the most important of which are generics, anonymous methods, iterators and incomplete types (partial types).
Generics allow classes, structures, interfaces, delegates, and methods to be parameterized by the type of data they store and manipulate. Generics are useful because they provide stronger compile-time type checking, reducing explicit conversions between data types, as well as boxing operations and run-time type checking.
Anonymous methods allow code blocks to sneak inline where the delegate value is expected. Anonymous methods are similar to lambda functions in the Lisp programming language. C# 2.0 supports the creation of "closures" in which anonymous methods can access relevant local variables and parameters.
Iterator is a method that can incrementally calculate and generate values. Iterators make it easy for a type to specify how a foreach statement iterates over all of its elements.
Incomplete types allow classes, structures and interfaces to be split into multiple parts and stored in different source files, which is more conducive to development and maintenance. In addition, incomplete types allow separation between machine-generated and user-written parts of certain types, so augmenting the code produced by the tool is easy.
This chapter will introduce these new features. After this introduction, the next four chapters provide complete technical specifications of these features.
C# 2.0 language extensions are primarily designed to ensure maximum compatibility with existing code. For example, although C# 2.0 assigns special meaning to the words where, yield, and partial in specific contexts, these words can still be used as identifiers. In fact, C# 2.0 does not add any keywords that might conflict with identifiers in existing code.
19.1 Generics
Generics allow classes, structures, interfaces, delegates, and methods to be parameterized by the type of data they store and manipulate. C# generics will be familiar to users of Eiffel or Ada's generics, or to users of C++ templates; but they will no longer have to endure the many complexities of the latter.
19.1.1 Why use generics
Without generics, a general-purpose data structure can use the object type to store any type of data. For example, the following Stack class stores data in an object array, and its two methods, Push and Pop, use objects to receive and return data accordingly.
public class Stack { object[] items; int count; public void Push(object item){…} public object Pop(){…} }
Although using type object can make the Stack class more flexible, it is not without its shortcomings. For example, you can push a value of any type, such as an instance of Customer, onto the stack. But when you get back a value, the result of the Pop method must be explicitly cast to the appropriate type, and it's annoying to write code for a runtime type check, and the resulting performance penalty.
Stack stack = new Stack(); Stack.Push(new Customer()); Customer c = (Customer)stack.Pop();
If a value type, such as an int, is passed to the Push method, it will be automatically boxed. When the int is later obtained, it must be unboxed using an explicit cast.
Stack stack = new Stack(); Stack.Push(3); int I = (int)stack.Pop();
Such boxing and unboxing operations add performance overhead because they involve dynamic memory allocation and runtime type checking.
The bigger problem with the Stack class is that it cannot enforce the kind of data placed on the stack. In fact, a Customer instance can be pushed onto the stack and cast to the wrong type when retrieved.
Stack stack = new Stack(); Stack.Push(new Customer()); String s = (string)stack.Pop();
Although the previous code was an inappropriate use of the Stack class, this code is technically correct and does not report a compile-time error. The problem won't arise until the code is executed, at which point an InvalidCastException will be thrown.
If the Stack class had the ability to specify the type of its elements, then it would obviously benefit from this ability. Using generics, this becomes possible.
19.1.2 Creating and using generics
Generics provide tools for creating types with type parameters. The following example declares a generic Stack class with a type parameter T. Type parameters are specified in the "<" and ">" delimiters after the class name. There is no conversion between object and other types; instances of Stack
Public class Stack<T> { T[] items; int count; public void Push(T item){…} public T Pop(){…} }
当泛型类Stack
Stack<int> stack = new Stack<int>(); Stack.Push(3); int x = stack.Pop();
Stack
泛型提供了强类型,意义例如压入一个int到Customer对象堆栈将会出现错误。就好像Stack
对于下面的例子,编译器将会在最后两行报告错误。
Stack<Customer> stack = new Stack<Customer>(); Stack.Push(new Customer()); Customer c = stack.Pop(); stack.Push(3); //类型不匹配错误 int x = stack.Pop(); //类型不匹配错误
泛型类型声明可以有任意数量的类型参数。先前的Stack
public class Dictionary<K , V> { public void Add(K key , V value){…} public V this[K key]{…} } 当Dictionary<K , V> 被使用时,必须提供两个类型参数。 Dictionary<string , Customer> dict = new Dictionary<string , Customer>(); Dict.Add(“Peter”, new Customer()); Custeomer c = dict[“Perter”];
19.1.3泛型类型实例化
与非泛型类型相似,被编译过的泛型类型也是由中间语言[Intermediate Language(IL)]指令和元数据表示。泛型类型的表示当然也对类型参数的存在和使用进行了编码。
当应用程序首次创建一个构造泛型类型的实例时,例如,Stack
.NET公共语言运行时使用值类型为每个泛型类型实例创建了一个本地代码的特定拷贝,但对于所有的引用类型它将共享那份本地代码的单一拷贝(因为,在本地代码级别,引用只是带有相同表示的指针)。
19.1.4约束
一般来讲,泛型类不限于只是根据类型参数存储值。泛型类经常可能在给定类型参数的类型的对象上调用方法。例如,Dictionary
public class Dictionary<K , V> { public void Add(K key , V value) { … if(key.CompareTo(x)<0){…}//错误,没有CompareTo方法 … } }
因为为K所指定的类型参数可能是任何类型,可以假定key参数存在的唯一成员,就是那些被声明为object类型的,例如,Equals,GetHashCode和ToString;因此,在先前例子中将会出现编译时错误。当然,你可以将key参数强制转换到一个包含CompareTo方法的类型。例如,key参数可能被强制转换到IComparable接口。
public class Dictionary<K , V> { public void Add(K key , V value) { … if(((IComparable)key).CompareTo(x)<0){…} … } }
尽管这种解决办法有效,但它需要在运行时的动态类型检查,这也增加了开销。更糟糕的是,它将错误报告推迟到了运行时,如果键(key)没有实现IComparable接口将会抛出InvalidCastException异常。
为了提供更强的编译时类型检查,并减少类型强制转换,C#允许为每个类型参数提供一个约束(constraint)的可选的列表。类型参数约束指定了类型必须履行的一种需求,其目的是为了为类型参数被用作实参(argument)。约束使用单词where声明,随后是类型参数的名字,接着是类或接口类型的列表,和可选的构造函数约束new()。
public class Dictionary<K, V> where K :IComparable { public void Add(K key , V value) { … if(key.CompareTo(x)<0){…} … } }
给定这个声明,编译器将会确保K的任何类型实参是实现了IComparable接口的类型。
并且,在调用CompareTo方法之前也不再需要对key参数进行显式地强制转换。为类型参数作为一个约束而给出的类型的所有成员,对于类型参数类型的值时直接有效的。
对于一个给定的类型参数,你可以指定任意数量的接口作为约束,但只能有一个类。每个约束的类型参数有一个单独的where 语句。在下面的例子中,类型参数K有两个接口约束,类型参数e有一个类约束和一个构造函数约束。
public class EntityTable<K, E> where K:IComparable<K>,IPersisable where E:Entity, new() { public void Add(K key , E entity) { … if(key.CompareTo(x)<0){…} … } }
在前面的例子中,构造函数约束new(),确保为E用作类型参数的类型具有一个公有的、无参数构造函数,并且它允许泛型类使用new E()创建该类型的实例。
类型参数约束应该很小心的使用。尽管它们提供了更强的编译时类型检查,在某些情况下增强了性能,但它们也限制了泛型类型的可能的用法。例如,泛型类List
以上就是C# 2.0 Specification(一)简介的内容,更多相关内容请关注PHP中文网(www.php.cn)!