• C# Array类的浅复制Clone()与Copy()的区别


    1 Array.Clone方法

    命名空间:System

    程序集:mscorlib

    语法:

    public Object Clone()

    Array的浅表副本仅复制Array的元素,无论他们是引用类型还是值类型,但是不负责这些引用所引用的对象。

    新Array中的引用与原始Array的引用指向相同的对象。

    例:

    int[] intArray1 = {1, 2};

    int [] intArray2 = (int [])intArray1.Clone();

    这里需要说明的是,需要使用强制类型转换,原因在于Clone()返回的类型为Object

    2 Array.Copy方法

    命名空间:System

    程序集:mscorlib

    Copy有几个重载函数:

    //从第一个元素开始复制Array中的一系列元素,将它们粘贴到另一Array中(从第一个元素开始)。长度为32位整数

    public static void Copy(Array sourceArray, Array destinationArray, int length)

    //从第一个元素开始复制Array中的一系列元素,将它们粘贴到另一Array中(从第一个元素开始)。长度为64位整数

    public static void Copy(Array sourceArray, Array destinationArray, long length)

    //从指定的源索引开始,复制Array中的一系列元素,将它们粘贴到另一Array中(从指定的目标索引开始)。长度和索引指定为32位整数

    public static void Copy(Array sourceArray, int sourceIndex,Array destinationArray, int destinationIndex,int length)

    //从指定的源索引开始,复制Array中的一系列元素,将它们粘贴到另一Array中(从指定的目标索引开始)。长度和索引指定为64位整数

    public static void Copy(Array sourceArray, long sourceIndex,Array destinationArray, long destinationIndex,long length)

    例: Array myIntArray=Array.CreateInstance( typeof(System.Int32), 5 );

    for ( int i = myIntArray.GetLowerBound(0); i <= myIntArray.GetUpperBound(0); i++ )

    {myIntArray.SetValue( i+1, i );}

    Array myObjArray = Array.CreateInstance( typeof(System.Object), 5 );

    for ( int i = myObjArray.GetLowerBound(0); i <= myObjArray.GetUpperBound(0); i++ )

    {myObjArray.SetValue( i+26, i );}

    // Copies the first element from the Int32 array to the Object array.

    Array.Copy( myIntArray, myIntArray.GetLowerBound(0), myObjArray, myObjArray.GetLowerBound(0), 1 );

    // Copies the last two elements from the Object array to the Int32 array.

    Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 );

    区别:

    Clone()返回值是Object,Copy返回值为void

    Clone()是非静态方法,Copy为静态方法。

    Clone()会创建一个新数组,Copy方法必须传递阶数相同且有足够元素的已有数组。

  • 相关阅读:
    D3js-实现图形拖拽及双击恢复
    D3js-三种图表tooltip提示框总结介绍
    D3js-API介绍【英】
    D3js-API介绍【中】
    springboot 整合 activemq 同时使用点对点模式和发布订阅模式
    docker 安装 activemq
    nginx 配置websocket 400 问题
    springboot +vue 整合websocket 403
    m3u8下载器
    linux scp 命令
  • 原文地址:https://www.cnblogs.com/vaevvaev/p/6862432.html
Copyright © 2020-2023  润新知