.Net Framework Programming 读书笔记(12)
14.0 数组
数组允许我们将多个数据项视作一个单独的集合。
所有数组类型都隐含继承自System.Array本身有继承自System.Object。数组总是分配在托管堆上。
CLR会验证数组索引的有效性。
14.1 所有数组的基类:System.Array
Array实现接口:ICloneable,IEnumberable,ICollection,IList
具体参见:System.Array成员。
14.2 数组的转型
必须存在显式/隐式的转换。CLR不许将元素为值类型的数组转为任何其他类型;但可使用--Array.Copy
Copy方法:
--将值类型元素装箱为引用类型元素。
--将引用类型元素拆箱为值类型元素。
--拓宽(widen)CLR基元类型。
14.3 数组的传递与返回
数组总是以引用方式传递给方法。
我们定一个返回数组引用的方法GetAppointmentsForToday(),MS建议该方法应返回一个0长数组。下面代码正常运行:
//容易理解
Appointment[] appointments = GetAppointmentsForToday();
for(Int32 a=0,n=appointments.Length;a<n;a++){...}
//不容易理解
Appointment[] appointments = GetAppointmentsForToday();
if(appointments!=null){
for(Int32 a=0,n=appointments.Length;a<n;a++){...}
}
14.4 创建下限非0的数组
//创建二维数组:[1995-2004],[1..4]季度
Int32[] lowerBounds = {1995,1};
Int32[] lengths = {10,4}
Decimal[,] quarterlyRevenue = (Decimal[,])Array.CreateInstance
(typeof(Decimal),lengths,lowerBounds);
Int32 firstYear = quarterlyRevenue.GetLowerBound(0);
Int32 lastYear = quarterlyRevenue.GetUpperBound(0);
Console.WriteLine("{0,4} {1,9} {2,9}, {3,9}, {4,9}","year","Q1","Q2","Q3","Q4")
for(Int32 year=firstYear;year<=lastYear;yeat++){
Console.Write(year + " ");
for(Int32 quarter=quarterlyRevenue.GetLowerBount(1)){
Console.Write("{0,9:C} ",quarterlyRevenue[year,quarter]);
}
Console.WriteLine();
}
14.5 快速数组访问
访问一个数组时不让CLR执行索引检测,提高性能:
using System;
class App{
unsafe static void Main(){
Int32[] arr = new Int32[] {1,2,3,4,5}; //创建一个5元素Int32 数组
fixed(Int32* element= &arr[0]){
//遍历数组中每一个元素
//注意:下面的代码中有BUG
for(Int32 x=0,n=arr.Length;x<=n;x++){
Console.WriteLine(element[x]);
}
}
}
}
说明:“x<=n”,不正确。输出将是 1/2/3/4/5/0 。所以 改为“x<n”。
14.6 重新调整数组长度
使用CreateInstance方法,重新调整一个数组的长度。
浙公网安备 33010602011771号