c#中数组赋值方法
2011-08-26 10:08
260 查看
C#中数组复制有多种方法
数组间的复制,int[] pins = {9,3,4,9};int [] alias = pins;这里出了错误,也是错误的根源,以上代码并没有出错,但是根本不是复制,因为pins和alias都是引用,存在于堆栈中,而数据9,3,4,3是一个int对象存在于堆中,int [] alias = pins;只不过是创建另一个引用,alias和pins同时指向{9,3,4,3},当修改其中一个引用的时候,势必影响另一个。复制的意思是新建一个和被复制对象一样的对象,在C#语言中应该有如下4种方法来复制。
方法一:使用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数组,这个例子可以灵活变通,很多地方可以用
数组间的复制,int[] pins = {9,3,4,9};int [] alias = pins;这里出了错误,也是错误的根源,以上代码并没有出错,但是根本不是复制,因为pins和alias都是引用,存在于堆栈中,而数据9,3,4,3是一个int对象存在于堆中,int [] alias = pins;只不过是创建另一个引用,alias和pins同时指向{9,3,4,3},当修改其中一个引用的时候,势必影响另一个。复制的意思是新建一个和被复制对象一样的对象,在C#语言中应该有如下4种方法来复制。
方法一:使用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数组,这个例子可以灵活变通,很多地方可以用
相关文章推荐
- c#中数组赋值方法
- C#读取对象实例的值和对对象的属性自动赋值方法
- C语言可以给字符数组赋值的方法
- C#中数组复制的四种方法
- C# 一个数组未赋值引发的错误
- C#乱序数组的简单方法
- php数组操作之键名比较与差集、交集赋值的方法
- C# 拷贝数组的几种方法
- C#控件数组使用方法.
- C#中数组初始化与数组元素复制的方法
- c#数组赋值基础教程 Array
- 一维数组的另一种赋值方法
- 数组赋值给vector的快速方法
- C#各种反射动态赋值取值方法
- C# 方法返回未知长度数组
- C# 字符串,数组,日期常遇到的处理方法(持续更新)
- javascript:创建数组并赋值的三种方法
- c#复制数组的多种方法
- C# 中数组的复制的几种方法
- C#清除数组中数据的几种方法及性能比较