c#清空数组&初始化数组&动态数组

本文介绍了C#中数组的各种操作方法,包括清空数组、初始化、动态修改大小及使用List的AddRange方法等内容,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

清空数组>>>Array.Clear [去MSDN查看]

1 string[] str = new string[2];
2 for (int i = 0; i < str.Length; i++)
3     str[i] = i.ToString();
4 Array.Clear(str, 0, str.Length);
5 for (int i = 0; i < str.Length; i++)
6     Console.WriteLine(string.IsNullOrEmpty(str[i]) ? "null" : str[i]);
7 //输出结果:
8 //null
9 //null

初始化数组>>>Initialize [去MSDN查看]

只是用于初始化,如果数组子项已经被初始化,那么不会改变它的值.(删除下面代码 x[1] = 6; 试试)

 1 int[] x = new int[2];
 2 int[] y = new int[2];
 3 x[0] = 5; x[1] = 6;
 4 x.Initialize();
 5 y.Initialize();
 6 for (int i = 0; i < x.Length; i++)
 7     Console.WriteLine("x:{0}  y:{1}", x[i], y[i]);
 8 //输出结果:
 9 //x:5   y:0
10 //x:6   y:0

动态修改数组大小>>>Array.Resize [去MSDN查看]

处理流程是:先创建一个新的数组,然后把旧数组赋值过去.

 1 int[] x = new int[2];
 2 x[0] = 5; x[1] = 6;
 3 Array.Resize(ref x, x.Length + 2);
 4 for (int i = 0; i < x.Length; i++)
 5     Console.WriteLine("x[{0}]={1}",i, x[i]);
 6 //输出结果:
 7 //x[0]=5
 8 //x[1]=6
 9 //x[2]=0
10 //x[3]=0

如果数组较大,性能影响明显,建议用List<>的AddRange方法. [去MSDN查看]

 1 List<int> lst = new List<int>();
 2 lst.Add(3); lst.Add(4);
 3 int[] x = new int[2];
 4 x[0] = 5; x[1] = 6;
 5 lst.AddRange(x);
 6 for (int i = 0; i < lst.Count; i++)
 7     Console.WriteLine("lst[{0}]={1}", i, lst[i]);
 8 //输出结果:
 9 //lst[0]=3
10 //lst[1]=4
11 //lst[2]=5
12 //lst[3]=6

关于Array数组复制拷贝,倒叙,排序等,详情参见MSDN

转载于:https://www.cnblogs.com/xiii/p/7050010.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值