Csharp/C Sharp by API/System/Array

Материал из .Net Framework эксперт
Версия от 12:12, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Array.AsReadOnly

  
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class Starter {
    public static void Main() {
        int[] zArray = { 1, 2, 3, 4 };
        zArray[1] = 10;
        ReadOnlyCollection<int> roArray = Array.AsReadOnly(zArray);
        foreach (int number in roArray) {
            Console.WriteLine(number);
        }
        roArray[1] = 2; // compile error
    }
}


Array.BinarySearch

 
using System;
class MainClass
{
  public static void Main()
  {
    int[] intArray = {5, 2, 3, 1, 6, 9, 7, 14, 25};
    Array.Sort(intArray);
    
    int index = Array.BinarySearch(intArray, 5);
    Console.WriteLine("Array.BinarySearch(intArray, 5) = " + index);
  }
}


Array.Clone

  
using System;
using System.Collections.Generic;
public class Starter {
    public static void Main() {
        CommissionedEmployee[] salespeople =
                {new CommissionedEmployee("Bob"),
                 new CommissionedEmployee("Ted"),
                 new CommissionedEmployee("Sally")};
        Employee[] employees =
            (Employee[])salespeople.Clone();
        foreach (Employee person in
                employees) {
            person.Pay();
        }
    }
}
public class Employee {
    public Employee(string name) {
        m_Name = name;
    }
    public virtual void Pay() {
        Console.WriteLine("Paying {0}", m_Name);
    }
    private string m_Name;
}
public class CommissionedEmployee : Employee {
    public CommissionedEmployee(string name) :
        base(name) {
    }
    public override void Pay() {
        base.Pay();
        Console.WriteLine("Paying commissions");
    }
}


Array.ConvertAll

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

public class MainClass
{
    public static void Main()
    {
        string[] strArray = new string[] { "75.3", "25.999", "105.25" };
        double[] doubleArray = Array.ConvertAll<string, double>(strArray, Convert.ToDouble);
        Console.Write("Converted to doubles: ");
        Array.ForEach<double>(doubleArray, delegate(double x) { Console.Write(x + " "); });
        Console.WriteLine();
    }
}


Array.Copy

  
/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Copy an array. 
 
using System;  
  
public class CopyDemo {     
  public static void Main() {     
    int[] source = { 1, 2, 3, 4, 5 }; 
    int[] target = { 11, 12, 13, 14, 15 }; 
    int[] source2 = { -1, -2, -3, -4, -5 }; 
 
    // Display source. 
    Console.Write("source: "); 
    foreach(int i in source)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
    // Display original target. 
    Console.Write("Original contents of target: "); 
    foreach(int i in target)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
    // Copy the entire array. 
    Array.Copy(source, target, source.Length); 
 
    // Display copy. 
    Console.Write("target after copy:  "); 
    foreach(int i in target)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
    // Copy into middle of target. 
    Array.Copy(source2, 2, target, 3, 2); 
 
    // Display copy. 
    Console.Write("target after copy:  "); 
    foreach(int i in target)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
  } 
}


Array.CopyTo

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

public class MainClass
{
    public static void Main()
    {
        int[] srcArray = new int[] { 1, 2, 3 };
        int[] destArray = new int[] { 4, 5, 6, 7, 8, 9 };
        Array.Copy(srcArray, destArray, srcArray.Length);
        srcArray.CopyTo(destArray, 0);
        srcArray.CopyTo(destArray, 3);
        Array.Copy(srcArray, 0, destArray, 2, srcArray.Length);
    }
}


Array.Count

  
using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Adding 6 elements"); 
    al.Add("C"); 
    al.Add("A"); 
    al.Add("E"); 
    al.Add("B"); 
    al.Add("D"); 
    al.Add("F"); 
 
    Console.WriteLine("Add enough elements to force ArrayList to grow. Adding 20 more elements"); 
    
    for(int i=0; i < 20; i++) 
      al.Add((char)("a" + i)); 
    Console.WriteLine("Current capacity: " + 
                       al.Capacity); 
    Console.WriteLine("Number of elements after adding 20: " + 
                       al.Count); 
    Console.Write("Contents: "); 
    foreach(char c in al) 
      Console.Write(c + " "); 
    Console.WriteLine("\n"); 
  }
}


Array.CreateInstance

  
using System;
using System.Reflection;
public class Starter {
    public static void Main(string[] argv) {
        Assembly executing = Assembly.GetExecutingAssembly();
        Type t = executing.GetType(argv[0]);
        Array zArray = Array.CreateInstance(t, argv.Length - 2);
        for (int count = 2; count < argv.Length; ++count) {
            System.Object obj = Activator.CreateInstance(t, new object[] {argv[count]});
            zArray.SetValue(obj, count - 2);
        }
        foreach (object item in zArray) {
            MethodInfo m = t.GetMethod(argv[1]);
            m.Invoke(item, null);
        }
    }
}
public class MyClass {
    public MyClass(string info) {
        m_Info = "MyClass " + info;
    }
    public void ShowInfo() {
        Console.WriteLine(m_Info);
    }
    private string m_Info;
}
public class YClass {
    public YClass(string info) {
        m_Info = "YClass " + info;
    }
    public void ShowInfo() {
        Console.WriteLine(m_Info);
    }
    private string m_Info;
}
public class XClass {
    public XClass(string info) {
        m_Info = "XClass " + info;
    }
    public void ShowInfo() {
        Console.WriteLine(m_Info);
    }
    private string m_Info;
}


Array.Exists

 

using System;   
  
class MainClass {      
 
  static bool isCriteria(int v) { 
    if(v > 1) 
      return true; 
    return false; 
  } 
 
  public static void Main() {      
    int[] nums = { 1, 4, -1, 5, -9 }; 
    
    Console.Write("Contents of nums: ");  
    foreach(int i in nums)   
      Console.Write(i + " ");  
    Console.WriteLine();  
  
    if(Array.Exists(nums, isCriteria)) { 
      Console.WriteLine("nums contains a negative value."); 
 
      // Now, find first negative value. 
      int x = Array.Find(nums, isCriteria); 
      Console.WriteLine("First negative value is : " + x); 
    } 
  }      
}


Array.Find

 
using System;   
  
class MainClass {      
 
  static bool isCriteria(int v) { 
    if(v > 1) 
      return true; 
    return false; 
  } 
 
  public static void Main() {      
    int[] nums = { 1, 4, -1, 5, -9 }; 
    
    Console.Write("Contents of nums: ");  
    foreach(int i in nums)   
      Console.Write(i + " ");  
    Console.WriteLine();  
  
    if(Array.Exists(nums, isCriteria)) { 
      Console.WriteLine("nums contains a negative value."); 
 
      // Now, find first negative value. 
      int x = Array.Find(nums, isCriteria); 
      Console.WriteLine("First negative value is : " + x); 
    } 
  }      
}


Array.FindAll

  
using System;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        int[] zArray = { 1, 2, 3, 1, 2, 3, 1, 2, 3 };
        Predicate<int> match = new Predicate<int>(MethodA<int>);
        int[] answers = Array.FindAll(zArray, match);
        foreach (int answer in answers) {
            Console.WriteLine(answer);
        }
    }
    public static bool MethodA<T>(T number) where T : IComparable {
        int result = number.rupareTo(3);
        return result == 0;
    }
}


Array.ForEach

 
using System.Collections;  
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System;

public class MainClass
{
    public static void Main()
    {
        int[] array = new int[] { 8, 2, 3, 5, 1, 3 };
        Array.ForEach<int>(array, delegate(int x) { Console.Write(x + " "); });
        Console.WriteLine();
    }
}


Array.GetEnumerator()

 

using System;
using System.Collections;
class MainClass
{
   static void Main()
   {
      int[] intArray = { 10, 11, 12, 13 };         
      IEnumerator ie = intArray.GetEnumerator();   
      while (ie.MoveNext() == true)               
      {
         int i = (int)ie.Current;                 
         Console.WriteLine("{0}", i);             
      }
   }
}


Array.GetLength()

    
using System;
class MainClass
{
  public static void Main()
  {
    string[,] names = {
      {"J", "M", "P"},
      {"S", "E", "S"},
      {"C", "A", "W"},
      {"G", "P", "J"},
    };
    int numberOfRows = names.GetLength(0);
    int numberOfColumns = names.GetLength(1);
    Console.WriteLine("Number of rows = " + numberOfRows);
    Console.WriteLine("Number of columns = " + numberOfColumns);
  }
}


Array.GetLowerbound

   
using System;
public class MainClass
{
    static void Main() {
        int[,] twoDim = { {1, 2, 3},
                          {4, 5, 6},
                          {7, 8, 9} };
        for( int i = twoDim.GetLowerBound(0);
             i <= twoDim.GetUpperBound(0);
             ++i ) {
            for( int j = twoDim.GetLowerBound(1);
                 j <= twoDim.GetUpperBound(1);
                 ++j ) {
                Console.WriteLine( twoDim[i,j] );
            }
        }
    }
}


Array.GetUpperBound

   

using System;
public class ArrayTest {
    public static void Main( ) {
       int[] array_1 = new int[5];
      
       for( int i = array_1.GetLowerBound(0); i <= array_1.GetUpperBound(0); i++)
          array_1[i] = i+1;
       for( int j = array_1.GetLowerBound(0); j <= array_1.GetUpperBound(0); j++)
          Console.WriteLine("array_1[{0}] = {1}", j, array_1[j]);
    }
}


Array.IndexOf

    
using System;
class MainClass
{
  public static void Main()
  {
    int[] intArray = {1, 2, 1, 3};
    Console.WriteLine("intArray:");
    for (int i = 0; i < intArray.Length; i++)
    {
      Console.WriteLine("intArray[" + i + "] = " +
        intArray[i]);
    }
    
    int index = Array.IndexOf(intArray, 1);
    Console.WriteLine("Array.IndexOf(intArray, 1) = " + index);
    index = Array.LastIndexOf(intArray, 1);
    Console.WriteLine("Array.LastIndexOf(intArray, 1) = " + index);
  }
}


Array.LastIndexOf

    
using System;
class MainClass
{
  public static void Main()
  {
    int[] intArray = {1, 2, 1, 3};
    Console.WriteLine("intArray:");
    for (int i = 0; i < intArray.Length; i++)
    {
      Console.WriteLine("intArray[" + i + "] = " +
        intArray[i]);
    }
    
    int index = Array.IndexOf(intArray, 1);
    Console.WriteLine("Array.IndexOf(intArray, 1) = " + index);
    index = Array.LastIndexOf(intArray, 1);
    Console.WriteLine("Array.LastIndexOf(intArray, 1) = " + index);
  }
}


Array.Length

    
 
using System; 
 
class MainClass {  
  public static void Main() {  
    int[,,] nums = new int[10, 5, 6];  
 
    Console.WriteLine("Length of nums is " + nums.Length);  
  
  }  
}


Array.Rank

    
using System;
class MainClass {
    public static void PrintArray(int[] arr) {
        for (int i = 0; i < arr.Length; ++i)
            Console.WriteLine("OneDArray Row {0} = {1}", i, arr[i]);
    }
    public static void PrintArrayRank(int[,] arr) {
        Console.WriteLine("PrintArrayRank: {0} dimensions", arr.Rank);
    }

    public static void Main() {
        int[] x = new int[10];
        for (int i = 0; i < 10; ++i)
            x[i] = i;
        PrintArray(x);
        int[,] y = new int[10, 20];
        for (int k = 0; k < 10; ++k)
            for (int i = 0; i < 20; ++i)
                y[k, i] = i * k;
        PrintArrayRank(y);
    }
}


Array.Resize

  
using System;
public class Starter {
    public static void Main() {
        int[] zArray = { 1, 2, 3, 4 };
        Array.Resize<int>(ref zArray, 8);
        foreach (int number in zArray) {
            Console.WriteLine(number);
        }
    }
}


Array.Reverse

  
/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace ReverseAndSort
 {
    public class TesterReverseAndSort
    {
        public static void DisplayArray(object[] theArray)
        {
            foreach (object obj in theArray)
            {
                Console.WriteLine("Value: {0}", obj);
            }
            Console.WriteLine("\n");
        }
       public void Run()
       {
           String[] myArray =
             {
                 "Who", "is", "John", "Galt"
             };
           Console.WriteLine("Display myArray...");
           DisplayArray(myArray);
           Console.WriteLine("Reverse and display myArray...");
           Array.Reverse(myArray);
           DisplayArray(myArray);
           String[] myOtherArray =
             {
                 "We", "Hold", "These", "Truths",
                 "To", "Be", "Self", "Evident",
           };
           Console.WriteLine("Display myOtherArray...");
           DisplayArray(myOtherArray);
           Console.WriteLine("Sort and display myOtherArray...");
           Array.Sort(myOtherArray);
           DisplayArray(myOtherArray);
       }
       [STAThread]
       static void Main()
       {
          TesterReverseAndSort t = new TesterReverseAndSort();
          t.Run();
       }
    }
 }


Array.Reverse(nums, 1, 3)

  
/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Reverse an array. 
 
using System;  
  
public class ReverseDemo {     
  public static void Main() {     
    int[] nums = { 1, 2, 3, 4, 5 }; 
   
    // Display original order. 
    Console.Write("Original order: "); 
    foreach(int i in nums)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
    // Reverse the entire array. 
    Array.Reverse(nums); 
 
    // Display reversed order. 
    Console.Write("Reversed order: "); 
    foreach(int i in nums)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
    // Reverse a range. 
    Array.Reverse(nums, 1, 3); 
 
    // Display reversed order. 
    Console.Write("Range reversed: "); 
    foreach(int i in nums)  
      Console.Write(i + " "); 
    Console.WriteLine(); 
  } 
}


Array.Sort

    
using System;
class MainClass
{
  public static void Main()
  {
    char[] charArray = {"w", "e", "l", "c", "o", "m", "e"};
    Array.Sort(charArray);  // sort the elements
    Console.WriteLine("Sorted charArray:");
    for (int i = 0; i < charArray.Length; i++)
    {
      Console.WriteLine("charArray[" + i + "] = " +
        charArray[i]);
    }
  }
}


Array.Sort(names, Comparer.DefaultInvariant)

  
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Globalization;
class Program {
    static void DisplayNames(IEnumerable e) {
        foreach (string s in e)
            Console.Write(s + " - ");
    }
    static void Main(string[] args) {
        string[] names = {"Alabama", "Texas", "Washington", 
                 "Virginia", "Wisconsin", "Wyoming", 
                 "Kentucky", "Missouri", "Utah", "Hawaii", 
                 "Kansas", "Lousiana", "Alaska", "Arizona"};
        Thread.CurrentThread.CurrentCulture = new CultureInfo("fi-FI");
        Array.Sort(names);
        DisplayNames(names);
        Array.Sort(names, Comparer.DefaultInvariant);
        Console.WriteLine("\nsorted with invariant culture...");
        DisplayNames(names);
    }
}


Array.SyncRoot

  
using System;
using System.Threading;
public class Starter {
    public static void Main() {
        Array.Sort(zArray);
        Thread t1 = new Thread(new ThreadStart(DisplayForward));
        Thread t2 = new Thread(new ThreadStart(DisplayReverse));
        t1.Start();
        t2.Start();
    }
    private static int[] zArray = { 1, 5, 4, 2, 4, 2, 9, 10 };
    public static void DisplayForward() {
        lock (zArray.SyncRoot) {
            Console.Write("\nForward: ");
            foreach (int number in zArray) {
                Console.Write(number);
            }
        }
    }
    public static void DisplayReverse() {
        lock (zArray.SyncRoot) {
            Array.Reverse(zArray);
            Console.Write("\nReverse: ");
            foreach (int number in zArray) {
                Console.Write(number);
            }
            Array.Reverse(zArray);
        }
    }
}