| 发表于:2007-03-15 14:12:2513楼 得分:0 |
方括号 ([]) 用于数组、索引器和属性,也可用于指针。 数组类型是一种后跟 [] 的类型: int[] fib; // fib is of type int[], "array of int " fib = new int[100]; // create a 100-element int array 若要访问数组的一个元素,则用方括号括起所需元素的索引: fib[0] = fib[1] = 1; for( int i=2; i <100; ++i ) fib[i] = fib[i-1] + fib[i-2]; 如果数组索引超出范围,则会引发异常。 不能重载数组索引运算符;但类型可以定义采用一个或多个参数的索引器和属性。索引器参数括在方括号中(就像数组索引一样),但索引器参数可声明为任何类型(这与数组索引不同,数组索引必须为整数)。 例如,.net framework 定义 hashtable 类型,该类型将键和任意类型的值关联在一起。 collections.hashtable h = new collections.hashtable(); h[ "a "] = 123; // note: using a string as the index 方括号还用于指定属性(c# 编程指南): [attribute(allowmultiple=true)] public class attr { } 可以使用方括号来指定指针索引: unsafe fixed ( int* p = fib ) // p points to fib from earlier example { p[0] = p[1] = 1; for( int i=2; i <100; ++i ) p[i] = p[i-1] + p[i-2]; } 不执行边界检查。 | | |
|