Array.Length属性用于获取数组所有维度中元素的总数。基本上, 数组的长度是该数组所有维度所包含的元素总数。
语法如下:
public int Length { get;
}
适当的价值:此属性返回数组所有维度中的元素总数。如果数组中没有元素, 它也可以返回零。返回类型为System.Int32.
例外:此属性引发OverflowException如果数组是多维数组, 并且包含多个最大价值 元素。这里MaxValue是2147483647。
下面的程序说明了上面讨论的属性的用法:
示例1:
//C# program to find the
//the total number of
//elements in 1-D Array
using System;
namespace srcmini {class GFG {//Main Method
public static void Main()
{//declares a 1D Array of string.
string [] weekDays;
//allocating memory for days.
weekDays = new string [] { "Sun" , "Mon" , "Tue" , "Wed" , "Thu" , "Fri" , "Sat" };
//Displaying Elements of the array
foreach ( string day in weekDays)
Console.Write(day + " " );
Console.Write( "\nTotal Number of Elements: " );
//using Length property
Console.Write(weekDays.Length);
}
}
}
输出如下:
Sun Mon Tue Wed Thu Fri Sat Total Number of Elements: 7
示例2:
//C# program to find the total
//number of elements in the
//multidimensional Arrays
using System;
namespace srcmini {class GFG {//Main Method
public static void Main()
{//Two-dimensional array
int [, ] intarray = new int [, ] {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
//The same array with dimensions
//specified 4 row and 2 column.
int [, ] intarray_d = new int [4, 2] {{ 1, 2}, {3, 4}, {5, 6}, {7, 8}};
//Three-dimensional array.
int [, , ] intarray3D = new int [, , ] {{{ 1, 2, 3}, { 4, 5, 6}}, {{ 7, 8, 9}, {10, 11, 12}}};
//The same array with dimensions
//specified 2, 2 and 3.
int [, , ] intarray3Dd = new int [2, 2, 3] {{{1, 2, 3}, {4, 5, 6}}, {{ 7, 8, 9}, {10, 11, 12}}};
Console.Write( "Total Number of Elements in intarray: " );
//using Length property
Console.Write(intarray.Length);
Console.Write( "\nTotal Number of Elements in intarray_d: " );
//using Length property
Console.Write(intarray_d.Length);
Console.Write( "\nTotal Number of Elements in intarray3D: " );
//using Length property
Console.Write(intarray3D.Length);
Console.Write( "\nTotal Number of Elements in intarray3Dd: " );
//using Length property
Console.Write(intarray3Dd.Length);
}
}
}
输出如下:
Total Number of Elements in intarray: 8Total Number of Elements in intarray_d: 8Total Number of Elements in intarray3D: 12Total Number of Elements in intarray3Dd: 12
【如何在C#中查找数组的长度()】参考:
- https://docs.microsoft.com/en-us/dotnet/api/system.array.length?view=netframework-4.7.2
推荐阅读
- 如何在Golang中找到指针的长度()
- 什么是SEO文章(你为什么要写呢?以及如何写?)
- SEO关键词(如何选择更好的关键词进行优化())
- 如何在Python中获取类属性列表()
- 如何在Linux中安装Scala(详细步骤图解)
- 如何为C#安装和设置Visual Studio(步骤图解)
- 如何安装Android虚拟设备(AVD)(详细图解步骤)
- Linux基础篇-8MySQL与PHP安装与配置
- 操作系统课内实践(内存管理)