文档介绍:DEV 331深度探索 Microsoft Visual C#
付仲恺
微软特邀开发专家
C#
范型(Generics)
匿名方法(Anonymous methods)
可为空类型(Nullable types)
迭代器(Iterators)
局部类型(Partial types)
等等
100%向后兼容
public class List
{
private object[] elements;
private int count;
public void Add(object element) {
if (count == ) Resize(count * 2);
elements[count++] = element;
}
public object this[int index] {
get { return elements[index]; }
set { elements[index] = value; }
}
public int Count {
get { return count; }
}
}
范型(Generics)
public class List<T>
{
private T[] elements;
private int count;
public void Add(T element) {
if (count == ) Resize(count * 2);
elements[count++] = element;
}
public T this[int index] {
get { return elements[index]; }
set { elements[index] = value; }
}
public int Count {
get { return count; }
}
}
List intList = new List();
(1);
(2);
("Three");
int i = (int)intList[0];
List intList = new List();
(1); // Argument is boxed
(2); // Argument is boxed
("Three"); // Should be an error
int i = (int)intList[0]; // Cast required
List<int> intList = new List<int>();
(1); // No boxing
(2); // No boxing
("Three"); // Compile-time error
int i = intList[0]; // No cast required
范型(Generics)
为什么需要范型?
类型检查,不进行拆箱和类型强制转换
增加了代码重用机会(类型集合)
C#如何实现范型?
在运行时实例化,而不是编译时
类型检查在声明时,而不是实例化时进行
同时支持引用和值类型
完整的运行时类型信息
范型(Generics)
类型参数能够被应用于:
类,结构体,接口,委托类型
class Dictionary<K,V> {...}
struct HashBucket<K,V> {...}
interface IComparer<T> {...}
delegate R Function<A,R>(A arg);
Dictionary<string,Customer> customerLookupTable;
Dictionary<string,List<Order>> orderLookupTable;
Dictionary<string,int> wordCount;
范型(Generics)
类型参数能够被应用于:
类,结构体,接口,委托类型
方法
class Utils{
public static T[] CreateArray<T>(T value, int size) {
T[] result = new T[size];
for (int i = 0; i < size; i++) result[i] = value;
return result;
}
}
string[] names =