c#框架笔记--数组

来源:互联网 发布:淘宝五金冠店铺 编辑:程序博客网 时间:2024/06/05 22:38
数组
数组类型转换的工作过程:

    //创建一个2维FileStream数组
    FileStream[,] fs2dim = new FileStream[5, 10];
    
    //隐式转换为一个2维的Object数组
    Object[,] o2dim = fs2dim;
    
    //不能从2维数组转换为1维数组,编译器报错error CS00300:不能讲'Object[*,*]'类型转换为'System.IO.Stream'
    Stream[] sldim = (Stream[]) o2dim;
    
    //显示转换为2维Stream数组
    Stream[,] s2dim = (Stream[,]) o2dim;
    
    //显示转换为2维String 数组,能编译通过,但在运行时会抛出InvalidVastException异常
    String[,] st2dim = (String[,]) o2dim;
    
    //创建一个1维Int32数组(值类型)
    Int32[] ildim = new Int32[5];
    
    //不能把值类型的数组转换为其他任何类型,编译器报错error CS0030: 不能将'int[]类型转换为 Object[]'
    Object[] oldim = (Object[]) ildim;
    
    //创建一个新的数组,然后使用Array.Copy将数组中的每一个元素强制装换为目标数组中的元素类型
    //下面的代码创建了一个数组,其中包含的是对已装箱的Int32的应用
    Object[] obldim = new Object[ildim.Length];
    Array.Copy(ildim, obldim, ildim.Length);
    
    Copy方法能执行一下转换:
    1、把值类型的元素装箱为引用类型的元素,比如将一个Int32[]赋值为一个Object[]
    2、将引用类型的元素拆箱为值类型的元素,比如将一个Object[]赋值为一个Int32[]
    3、加宽CLR基元类型,比如将元素从一个Int32[]赋值到Double[]中
    4、在两个数组类型之间进行复制时,如果两个数组的类型是比匹配的,将进行向下类型转换
    
注意:
    1、如果只是需要把数组中的某些值复制的另外一个类型相同的数组,那使用System.Bufferde BlockCopy方法,
        他的执行速度快,只支持基元类型
    2、如果需要可靠地把一个数组中的元素赋值到另一个数组中,那使用System.Array.ConstrainedCopy方法,但必须
        保证源、目标数组的类型一致



        
非安全数组
    using System;
    
    public static class Program
    {
        public  static void Main()
        {
            StackallocDemo();
            InlineArrayDemo();
        }
        
        private static void StackallocDemo()
        {
            unsafe
            {
                const Int32 width = 20;
                Char *pc = stackalloc Char[width];        //在堆上分配数组
                
                String s = "Jeffery Richter";
                
                for(Int32 index = 0; index < width; index++)
                {
                    pc[width - index - 1] = (index < s.Length) ? s[index] : '.';
                }
                
                Console.WriteLine(new String(pc, 0, width));
            }
        }
        
        private static void InlineArraryDemo()
        {
            unsafe
            {
                CharArray ca;            //在堆上分配数组
                Int32 widthInBytes = sizeof(CharArray);
                Int32 width = widthInBytes / 2;
                
                String s = "Jeffery Richter";
                
                for(Int32 index = 0; index < width; index++)
                {
                    ca.Characters[width - index - 1] = (index < s.Length) ? s[index] : '.';
                }
                
                Console.WriteLine(new String(ca.Characters, 0, width));
            }
        }
        
        internal unsafe struct CharArray
        {
            //这个数组内嵌在结构中
            public fixed Char Characters[20];
        }
    }
原创粉丝点击