c#配列タイプ

配列タイプ

C#では、配列は実際にはオブジェクトであり、配列は同じ型のいくつかの変数を含むデータ構造です。

アレイの概要

配列には次のプロパティがあります。

  • アレイとすることができる一次元多次元または互い違いです。
  • 数値配列要素のデフォルト値はゼロに設定され、参照要素のデフォルト値はnullに設定されます。
  • 千鳥配列は配列の配列であるため、その要素は参照型であり、nullに初期化されます。
  • 配列のインデックスはゼロから始まります。n要素を持つ配列のインデックスは0からn-1です。
  • 配列要素は、配列型を含む任意の型にすることができます。
  • 抽象基本型から配列型配列は、誘導された参照型をこの型はIEnumerableおよびIEnumerable <T>を実装しているため、C#のすべての配列でforeach反復を使用できます

1次元配列

int[] array = new int[5];
string[] stringArray = new string[6];

この配列には、配列[0]から配列[4]までの要素が含まれています。new演算子は、配列を作成し、配列要素をデフォルト値に初期化するために使用されます。この例では、すべての配列要素がゼロに初期化されています。

配列の初期化

int[] array1 = new int[] { 1, 3, 5, 7, 9 };
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

多次元配列

配列は複数の次元を持つことができます。たとえば、次のステートメントは、4行2列の2次元配列を作成します。

int[,] array = new int[4, 2];

3次元(4、2、3)配列の作成を宣言します。

int[, ,] array1 = new int[4, 2, 3];

配列の初期化

// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12

レベルを指定せずに配列を初期化することもできます。

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

配列変数を宣言しても初期化しない場合は、new演算子を使用して配列をこの変数に割り当てる必要があります。次の例は、newの使用法を示しています。

int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

特定の配列要素に値を割り当てます。

array5[2, 1] = 25;

配列要素をデフォルト値に初期化します(千鳥配列を除く):

int[,] array6 = new int[10, 10];

千鳥配列

インターリーブ配列は、要素が配列である配列です。インターリーブされた配列の要素の次元とサイズは異なる場合があります。インターリーブされた配列は、「配列の配列」と呼ばれることもあります。

int[][] jaggedArray = new int[3][];

使用する前に、jaggedArrayの要素を初期化する必要があります。

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

各要素は1次元の整数配列です。最初の要素は5つの整数の配列、2番目は4つの整数の配列、3番目は2つの整数の配列です。

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

宣言時に配列を初期化します

int[][] jaggedArray2 = new int[][] 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

個々の配列要素にアクセスします。

// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

foreachを使用した配列

numbersという名前の配列を作成し、foreachステートメントで配列を反復処理します。

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.Write("{0} ", i);
}
// Output: 4 5 6 1 2 3 -2 -1 0

多次元配列、同じ方法を使用して要素を反復できます

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

メソッドに渡される1次元配列

int[] theArray = { 1, 3, 5, 7, 9 };
PrintArray(theArray);

printメソッドの部分的な実装。

void PrintArray(int[] arr)
{
    // Method code.
}

新しい配列を初期化して渡す

PrintArray(new int[] { 1, 3, 5, 7, 9 });

公式の例

class ArrayClass
{
    static void PrintArray(string[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
        }
        System.Console.WriteLine();
    }

    static void ChangeArray(string[] arr)
    {
        // The following attempt to reverse the array does not persist when
        // the method returns, because arr is a value parameter.
        arr = (arr.Reverse()).ToArray();
        // The following statement displays Sat as the first element in the array.
        System.Console.WriteLine("arr[0] is {0} in ChangeArray.", arr[0]);
    }

    static void ChangeArrayElements(string[] arr)
    {
        // The following assignments change the value of individual array 
        // elements. 
        arr[0] = "Sat";
        arr[1] = "Fri";
        arr[2] = "Thu";
        // The following statement again displays Sat as the first element
        // in the array arr, inside the called method.
        System.Console.WriteLine("arr[0] is {0} in ChangeArrayElements.", arr[0]);
    }

    static void Main()
    {
        // Declare and initialize an array.
        string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

        // Pass the array as an argument to PrintArray.
        PrintArray(weekDays);

        // ChangeArray tries to change the array by assigning something new
        // to the array in the method. 
        ChangeArray(weekDays);

        // Print the array again, to verify that it has not been changed.
        System.Console.WriteLine("Array weekDays after the call to ChangeArray:");
        PrintArray(weekDays);
        System.Console.WriteLine();

        // ChangeArrayElements assigns new values to individual array
        // elements.
        ChangeArrayElements(weekDays);

        // The changes to individual elements persist after the method returns.
        // Print the array, to verify that it has been changed.
        System.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
        PrintArray(weekDays);
    }
}
// Output: 
// Sun Mon Tue Wed Thu Fri Sat
// arr[0] is Sat in ChangeArray.
// Array weekDays after the call to ChangeArray:
// Sun Mon Tue Wed Thu Fri Sat
// 
// arr[0] is Sat in ChangeArrayElements.
// Array weekDays after the call to ChangeArrayElements:
// Sat Fri Thu Wed Thu Fri Sat

メソッドに渡される多次元配列

int[,] theArray = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
Print2DArray(theArray);

このメソッドは、パラメーターとして2次元配列を受け入れます。

void Print2DArray(int[,] arr)
{
    // Method code.
}

新しい配列を初期化して渡す

Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

公式の例

class ArrayClass2D
{
    static void Print2DArray(int[,] arr)
    {
        // Display the array elements.
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
            }
        }
    }
    static void Main()
    {
        // Pass the array as an argument.
        Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Element(0,0)=1
        Element(0,1)=2
        Element(1,0)=3
        Element(1,1)=4
        Element(2,0)=5
        Element(2,1)=6
        Element(3,0)=7
        Element(3,1)=8
    */

refとoutを使用して配列を渡す

配列型出力パラメーターを使用する前に、値を割り当てる必要があります。つまり、呼び出し先に値を割り当てる必要があります。

static void TestMethod1(out int[] arr)
{
    arr = new int[10];   // definite assignment of arr
}

すべてのrefパラメーターと同様に、配列型のrefパラメーターは呼び出し元が明示的に割り当てる必要があります。したがって、受信者が明示的に割り当てる必要はありません。配列型のrefパラメーターを呼び出しの結果に変更できます。

static void TestMethod2(ref int[] arr)
{
    arr = new int[10];   // arr initialized to a different array
}

呼び出し元(Mainメソッド)で配列theArrayを宣言し、FillArrayメソッドでこの配列を初期化します。次に、配列要素を呼び出し元に返し、表示します。

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        FillArray(out theArray);

        // Display the array elements:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1 2 3 4 5        
    */

呼び出し元(Mainメソッド)で配列theArrayを初期化し、refパラメーターを使用してそれをFillArrayメソッドに渡します。FillArrayメソッドの一部の配列要素を更新します。次に、配列要素を呼び出し元に返し、表示します

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        FillArray(ref theArray);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1111 2 3 4 5555
    */

暗黙的に型付けされた配列

暗黙的に型指定された配列を作成する方法:

class ImplicitlyTypedArraySample
{
    static void Main()
    {
        var a = new[] { 1, 10, 100, 1000 }; // int[]
        var b = new[] { "hello", null, "world" }; // string[]

        // single-dimension jagged array
        var c = new[]   
{  
    new[]{1,2,3,4},
    new[]{5,6,7,8}
};

        // jagged array of strings
        var d = new[]   
{
    new[]{"Luca", "Mads", "Luke", "Dinesh"},
    new[]{"Karen", "Suma", "Frances"}
};
    }
}

配列を含む匿名型を作成する場合、配列はその型のオブジェクト初期化子で暗黙的に型指定する必要があります。次の例では、contactsは暗黙的に型指定された匿名型の配列であり、各匿名型にはPhoneNumbersという名前の配列が含まれています。varキーワードは、オブジェクト初期化子の内部では使用されないことに注意してください。

var contacts = new[] 
{
    new {
            Name = " Eugene Zabokritski",
            PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
        },
    new {
            Name = " Hanying Feng",
            PhoneNumbers = new[] { "650-555-0199" }
        }
};

おすすめ

転載: www.cnblogs.com/ouyangkai/p/12753831.html