📜  C#|检查数组的大小是否固定

📅  最后修改于: 2021-05-29 18:38:09             🧑  作者: Mango

Array.IsFixedSize属性用于获取一个值,该值指示Array是否具有固定大小。此属性实现IList.IsFixedSize属性。

句法:

public bool IsFixedSize { get; }

属性值:对于所有数组,此属性始终返回true。

下面的程序说明了上面讨论的属性的用法:

范例1:

// C# program to illustrate
// IsFixedSize of Array class
using System;
namespace geeksforgeeks {
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // declares an 1D Array of string
        string[] topic;
  
        // allocating memory for topic.
        topic = new string[] {"Array, ", "String, ",
                               "Stack, ", "Queue, ",
                        "Exception, ", "Operators"};
  
        // Displaying Elements of the array
        Console.WriteLine("Topic of C#:");
  
        foreach(string ele in topic)
            Console.WriteLine(ele + " ");
  
        Console.WriteLine();
  
        // Here we check whether is
        // array of fixed size or not
        Console.WriteLine("Result: " + topic.IsFixedSize);
    }
}
}
输出:
Topic of C#:
Array,  
String,  
Stack,  
Queue,  
Exception,  
Operators 

Result: True

范例2:

// C# program to illustrate
// IsFixedSize of Array class
using System;
namespace geeksforgeeks {
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // declares a 1D Array of string 
        // and assigning null to it
        string[] str = new string[] {null};
  
        // Here we check whether is
        // array of fixed size or not
        Console.WriteLine("Result: " + str.IsFixedSize);
    }
}
}
输出:
Result: True

笔记:

  • Array实现了IsFixedSize属性,因为System.Collections.IList接口需要它。
  • 具有固定大小的数组不允许在创建数组后添加或删除元素,但允许修改现有元素。
  • 检索此属性的值是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.array.isfixedsize?view=netframework-4.7.2