Home  >  Article  >  Backend Development  >  Introduction to C# 2.0 Specification (1)

Introduction to C# 2.0 Specification (1)

黄舟
黄舟Original
2017-01-03 10:10:011453browse

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 "d21bf6265d53cdd4dcff18f6785f8fb4" delimiters after the class name. There is no conversion between object and other types; instances of Stack8742468051c85b06f0a0af9e3e506b5c accept the type they were created with and store data of that type without converting it. The type parameter T acts as a placeholder and does not specify an actual type until it is used. Note that T is used as the element type of the internal items array, the type of the Push method parameter, and the return value type of the Pop method.

Public class Stack<T>
{
T[] items;
int count;
public void Push(T item){…}
public T Pop(){…}
}

当泛型类Stack8742468051c85b06f0a0af9e3e506b5c被使用时,T所代替的实际类型将被指定。在下面的例子中,int 将被作为T的类型参数而给出。

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

Stackbd43222e33876353aff11e13a7dc75f6类型被称为构造类型(constructed type)。在Stackbd43222e33876353aff11e13a7dc75f6类型中,T的每次出现都被使用类型参数int代替。当Stackbd43222e33876353aff11e13a7dc75f6的实例被创建时,items数组的本地存储就是一个int[]而不是object[],与非泛型Stack相比,它提供了更高的存储效率。同样地,在int值上的Stackbd43222e33876353aff11e13a7dc75f6操作的Push和Pop方法,将会使得压入其他类型的值到堆栈中出现一个编译时错误,并且当取回值的时候也不需要转换回它们原始的类型。

泛型提供了强类型,意义例如压入一个int到Customer对象堆栈将会出现错误。就好像Stackbd43222e33876353aff11e13a7dc75f6被限制只能在int值上操作,同样Stackc214b1127c801bd6a2a45c5b466f54b2也被限制用于Customer对象。

对于下面的例子,编译器将会在最后两行报告错误。

Stack<Customer> stack = new Stack<Customer>();
Stack.Push(new Customer());
Customer c = stack.Pop();
stack.Push(3); //类型不匹配错误
int x = stack.Pop(); //类型不匹配错误

泛型类型声明可以有任意数量的类型参数。先前的Stack8742468051c85b06f0a0af9e3e506b5c例子 只有一个类型参数,但一个通用的Dictionary类可能有两个类型参数,一个用于键(key)的类型,另一个用于值(value)的类型。

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)]指令和元数据表示。泛型类型的表示当然也对类型参数的存在和使用进行了编码。

当应用程序首次创建一个构造泛型类型的实例时,例如,Stackbd43222e33876353aff11e13a7dc75f6,.NET公共语言运行时的实时编译器(JIT)将在进程中把泛型IL和元数据转换为本地代码,并且将类型参数替换为实际的类型。对于那个构造泛型类型的后续引用将会使用相同的本机代码。从一个泛型类型创建一个特定构造类型的过程,称为泛型类型实例化(generic type instantiation)。[/b]

.NET公共语言运行时使用值类型为每个泛型类型实例创建了一个本地代码的特定拷贝,但对于所有的引用类型它将共享那份本地代码的单一拷贝(因为,在本地代码级别,引用只是带有相同表示的指针)。

19.1.4约束

一般来讲,泛型类不限于只是根据类型参数存储值。泛型类经常可能在给定类型参数的类型的对象上调用方法。例如,Dictionarybfbf51059cfb0a0d14f2e5a287507931类中的Add方法可能需要使用CompareTo方法比较键值。

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()创建该类型的实例。

类型参数约束应该很小心的使用。尽管它们提供了更强的编译时类型检查,在某些情况下增强了性能,但它们也限制了泛型类型的可能的用法。例如,泛型类List8742468051c85b06f0a0af9e3e506b5c可能约束T实现IComparable接口,由此它的Sort方法将可以比较项的大小。然而,这么做却使得没有实现IComparable 接口的类型不能使用List8742468051c85b06f0a0af9e3e506b5c,即使是在这些情形下,Sort方法根本就没有被调用过。

以上就是C# 2.0 Specification(一)简介的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn