尽管 longlength 属性提供长整型值,但请务必记住,c# 中数组的最大大小仍然受到系统支持的内存量的限制。如果您尝试构建太大的数组,可能会引发 outofmemoryexception。
语法public long longlength { get; }
long − 64位整数值,表示数组中元素的数量。
整个数组中的元素数量通过c#中数组的longlength属性作为长整数返回。当处理可能包含超过20亿元素(32位整数的最大容量)的大数组时,这个属性非常有用。在这种情况下,length属性会返回一个负值,表示溢出问题。通过返回一个能够表示更高值的长整数,longlength属性解决了这个问题。
示例在这个程序中,我们创建了一个包含10亿个整数的数组,并给每个元素赋值。然后,我们使用length和longlength属性来获取数组中的元素数量。length属性由于整数溢出而返回一个负数,而longlength属性以长整数的形式返回正确的元素数量。
算法步骤-1 − 创建一个任意类型的数组,例如 int[] abc= new int[1000000000];
step-2 - 为数组元素赋值,例如 abc[0] = 1; abc[1] = 2; ... abc[999999999] = 1000000000;
step-3 - 使用 length 属性获取数组中的元素数量。由于整数溢出,这将返回负数,因为该数组有超过 20 亿个元素。
step-4 - 使用 longlength 属性以长整数形式获取数组中的元素总数。这将返回正确的数字,即 1000000000。
using system;class program { static void main(string[] args) { //initilize an array of 1000000000 elements int[] arr = new int[1000000000]; for (int i = 0; i < arr.length; i++) //loop to assign values to array you can do this without loop but its a large array so loop is needed { arr[i] = i + 1; } console.writeline(length: + arr.length);// length property console.writeline(longlength: + arr.longlength);//longlength property }}
输出length: 1000000000
示例您可以计算2维或3维数组中的元素数量。这有助于准确计算复杂数组中的元素数量。在这个例子中,我们将创建一个2维数组,并使用longlength属性计算2维数组的元素数量。
步骤 1 - 声明一个 int 数据类型的二维数组,并用一些值进行初始化。
第二步 - 获取数组的longlength属性。
第三步 - 将longlength属性的值打印到控制台。
using system;class program { static void main(string[] args) { // declare and initialize a 2-d array of integers int [,] a = new int [3,4] { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} }; // get the longlength property of the array long length = a.longlength; // print the value of the longlength property to the console console.writeline(the length of the array is: + length); }}
输出the length of the array is: 12
结论当处理超出整数限制的大型数组时,c# 中数组的 longlength 属性是一个有用的属性。它允许我们处理几乎任何大小的数组,唯一的限制是系统可用的内存量。它以长整型值的形式返回数组可以携带的元素数量。
以上就是c# 中数组的 longlength 属性的详细内容。
