java copyto,【转载】 C#中使用CopyTo方法将List集合元素拷贝到数组Array中

在C#的List集合操作中,有时候需要将List元素对象拷贝存放到对应的数组Array中,此时就可以使用到List集合的CopyTo方法来实现,CopyTo方法是List集合的扩展方法,共有3个重载方法签名,分别为void CopyTo(T[] array)、void CopyTo(T[] array, int arrayIndex)、void CopyTo(int index, T[] array, int arrayIndex, int count)等三种形式,此文重点介绍CopyTo的第一种方法签名形式void CopyTo(T[] array)。

首先定义个用于测试的类TestModel,具体的类定义如下:

public classTestModel

{public int Index { set; get; }public string Name { set; get; }

}

然后定义一个List集合,并往里面写入3条TestModel数据,具体实现如下:

List testList = new List();

testList.Add(newTestModel()

{

Index=1,

Name="Index1"});

testList.Add(newTestModel()

{

Index= 2,

Name= "Index2"});

testList.Add(newTestModel()

{

Index= 3,

Name= "Index3"});

我们需要达到的目的是,将testList集合的元素对象拷贝到数组Array中,此时可使用下列语句实现:

TestModel[] copyArray = newTestModel[testList.Count];

testList.CopyTo(copyArray);

注意:上述程序语句中的CopyTo方法为浅层次拷贝,当修改copyArray数组的时候,也会联动修改List集合对象testList。例如赋值copyArray[0].Index = 10后,List集合对象testList的第一个元素testList[0]对象的Index属性也被修改为10。

博主个人技术交流群:960640092,博主微信公众号如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值