2010年9月22日水曜日

C# の配列の初期化について

メモ、on Mono 2.6.7


なるほどな。

それはそれとして、C# では、
  1. using System;  
  2.   
  3. namespace Example  
  4. {  
  5.   public static class Ext  
  6.   {  
  7.     public static T[] InitializeWith<T>(this T[] array, T val)  
  8.     {  
  9.       for (int i = 0; i < array.Length; i++)  
  10.       {  
  11.         array[i] = val;  
  12.       }  
  13.   
  14.       return array;  
  15.     }  
  16.   
  17.     public static void Print<T>(this T[] array, string separater)  
  18.     {  
  19.       foreach (T t in array)  
  20.       {  
  21.         Console.Write("{0}{1}", t.ToString(), separater);  
  22.       }  
  23.   
  24.       Console.WriteLine("\b ");  
  25.     }  
  26.   }  
  27.   
  28.   public class Program  
  29.   {  
  30.     public static void Main(string[] args)  
  31.     {  
  32.       //int[] ar0 = new int[3]{0}; // error CS0847: An array initializer of length `3' was expected  
  33.       //int[] ar0 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected  
  34.       int[] ar0 = new int[3];  
  35.   
  36.       int[] ar1 = new int[3]{ 1, 2, 3 };  
  37.       int[] ar2 = new int[]{ 4, 5, 6 };  
  38.       int[] ar3 = { 7, 8, 9 };  
  39.       var ar4 = new []{ 0, 1, 2 };  
  40.   
  41.       int[] ar5 = new int[3].InitializeWith(1);  
  42.   
  43.       ar0.Print(","); // 0,0,0  
  44.       ar1.Print(","); // 1,2,3  
  45.       ar2.Print(","); // 4,5,6  
  46.       ar3.Print(","); // 7,8,9  
  47.       ar4.Print(","); // 0,1,2  
  48.       ar5.Print(","); // 1,1,1  
  49.     }  
  50.   }  
  51. }  
  52. /* 
  53.  * Build: 
  54.  * 
  55.  *   gmcs array.cs 
  56.  * 
  57.  * Run: 
  58.  * 
  59.  *   mono array.exe 
  60.  * 
  61.  */  
宣言時に初期化(配列初期化子({...})で設定)しなかった場合、配列の全要素は、配列の型の規定値で初期化される。型の規定値については、「MSDN:Default Values Table (C# Reference)」を参照。

任意の値で配列の全要素を設定(初期化)したい場合は、拡張メソッド等を用意してやればいいのかな。

1 件のコメント:

sta さんのコメント...

Before:
public static void Print<T>(this T[] array, string title)

After:
public static void Print<T>(this T[] array, string separater)

に伴う変更を行いました。

コメントを投稿