C#中怎么复制数组?C#复制数组的5种方法

方法一:使用for循环

int []pins = {9,3,7,2}
int []copy = new int[pins.length];
for(int i =0;i!=copy.length;i++)
{
copy[i] = pins[i];
}

方法二:使用数组对象中的CopyTo()方法

int []pins = {9,3,7,2}
int []copy2 = new int[pins.length];
pins.CopyTo(copy2,0);

方法三:使用Array类的一个静态方法Copy()

int []pins = {9,3,7,2}
int []copy3 = new int[pins.length];
Array.Copy(pins,copy3,copy.Length);

方法四:使用Array类中的一个实例方法Clone(),可以一次调用,最方便,但是Clone()方法返回的是一个对象,所以要强制转换成恰当的类类型。

int []pins = {9,3,7,2}
int []copy4 = (int [])pins.Clone();

方法五:

string[] student1 = { "$", "$", "c", "m", "d", "1", "2", "3", "1", "2", "3" };
string[] student2 = { "0", "1", "2", "3", "4", "5", "6", "6", "1", "8", "16","10","45", "37", "82" };
ArrayList student = new ArrayList();   
foreach (string s1 in student1)
{
      student.Add(s1);                
}
foreach (string s2 in student2)
{
      student.Add(s2);
}
string[] copyAfter = (string[])student.ToArray(typeof(string));

两个数组合并,最后把合并后的结果赋给copyAfter数组,这个例子可以灵活变通,很多地方可以用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值