Csharp/CSharp Tutorial/Data Structure/Array Clone
Версия от 15:31, 26 мая 2010; (обсуждение)
Clone array with reference data inside
using System;
class MyClass
{
public int Value = 5;
}
class MainClass
{
static void Main()
{
MyClass[] orignalArray = new MyClass[3] { new MyClass(), new MyClass(), new MyClass() };
MyClass[] cloneArray = (MyClass[])orignalArray.Clone();
cloneArray[0].Value = 1;
cloneArray[1].Value = 2;
cloneArray[2].Value = 3;
foreach (MyClass a in orignalArray)
Console.WriteLine(a.Value);
foreach (MyClass a in cloneArray)
Console.WriteLine(a.Value);
}
}
1 2 3 1 2 3
Clone Value Array
using System;
class MainClass
{
static void Main()
{
int[] orignalArray = { 1, 2, 3 };
int[] cloneArray = (int[])orignalArray.Clone();
cloneArray[0] = 10;
cloneArray[1] = 20;
cloneArray[2] = 30;
foreach (int i in orignalArray)
Console.WriteLine(i);
foreach (int i in cloneArray)
Console.WriteLine(i);
}
}
1 2 3 10 20 30
Cloning arrays
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
class GoodMonthType {
private static readonly string[] monthConstants = new string[] {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
public string[] Months
{
get { return (string[])monthConstants.Clone(); }
}
public IEnumerable<string> MonthsEnumerable
{
get { return Array.AsReadOnly<string>(monthConstants); }
}
}
public class MainClass
{
public static void Main()
{
GoodMonthType mt2 = new GoodMonthType();
foreach (string m in mt2.Months) {
Console.WriteLine(m);
}
string[] months2 = mt2.Months;
months2[3] = "Not-April";
foreach (string m in mt2.Months) {
Console.WriteLine(m);
}
}
}
January February March April May June July August September October November December January February March April May June July August September October November December