现在的位置: 首页 > 综合 > 正文

创建基于栈的数组

2012年03月08日 ⁄ 综合 ⁄ 共 647字 ⁄ 字号 评论关闭
using System;

namespace exercise {
    class Program {
        static unsafe void Main(string[] args) {
            //创建基于栈的数组
            decimal* pDecimals = stackalloc decimal[10];

            int size;
            size = 20; //or some other value calculated at runtime
            double* pDoubles = stackalloc double[size];
            //把第一个元素(数组元素0)设置为3.0
            *pDoubles = 3.0; // pDoubles[0] is the same as *pDoubles
            //把数组的第二个元素(元素编号1)设置为8.4
            *(pDoubles + 1) = 8.4; // pDoubles[1] is the same as *(pDoubles +1)
            //可以用表达式 *(pDoubles + X) 访问数组中下标为X的元素。
            //如果p是任意指针类型,X是一个整数,表达式 p[X]就会被编译器解释为*(p + X),这适合于所有指针。

            //下面的代码会抛出一个异常,抛出异常的原因是:使用越界的下标来访问数组
            double[] myDoubleArray = new double[20];
            myDoubleArray[50] = 3.0;
            //如果使用stackalloc声明一个等价的数组,对数组进行辩解检查时,这个数组中就没有封装任何对象,
            //因此下面的代码不会抛出异常:
            pDoubles[50] = 3.0;

        }
    }
}

--摘自《C#高级编程》

抱歉!评论已关闭.