Csharp/CSharp Tutorial/Data Structure/Array Clone — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 12:15, 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