当前位置: 移动技术网 > IT编程>开发语言>c# > c#数组类型

c#数组类型

2020年04月23日  | 移动技术网IT编程  | 我要评论
数组类型 在 C 中,数组实际上是对象,数组是一种数据结构,它包含若干相同类型的变量。 数组概述 数组具有以下属性: 数组可以是 "一维" 、 "多维" 或 "交错" 的。 数值数组元素的默认值设置为零,而引用元素的默认值设置为 null。 交错数组是数组的数组,因此其元素是引用类型并初始化为 nu ...

数组类型

在 c# 中,数组实际上是对象,数组是一种数据结构,它包含若干相同类型的变量。

数组概述

数组具有以下属性:

  • 数组可以是 一维多维交错的。
  • 数值数组元素的默认值设置为零,而引用元素的默认值设置为 null。
  • 交错数组是数组的数组,因此其元素是引用类型并初始化为 null。
  • 数组的索引从零开始:具有 n 个元素的数组的索引是从 0 到 n-1。
  • 数组元素可以是任何类型,包括数组类型。
  • 数组类型是从抽象基类型 array 派生的 引用类型。 由于此类型实现了 ienumerableienumerable< t> ,因此可以对 c# 中的所有数组使用foreach 迭代。

一维数组

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

此数组包含从 array[0] 到 array[4] 的元素。 new 运算符用于创建数组并将数组元素初始化为它们的默认值。 在此例中,所有数组元素都初始化为零。

数组初始化

int[] array1 = new int[] { 1, 3, 5, 7, 9 };
string[] weekdays = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };

多维数组

数组可以具有多个维度。 例如,下列声明创建一个四行两列的二维数组。

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

声明创建一个三维(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];

每个元素都是一个一维整数数组。 第一个元素是由 5 个整数组成的数组,第二个是由 4 个整数组成的数组,而第三个是由 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

一维数组传递给方法

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);

该方法接受一个二维数组作为其参数。

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 传递数组

使用数组类型的 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" }
        }
};

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网