Array.IsReadOnly属性用于获取一个值,该值指示Array是否为只读。
句法:
public bool IsReadOnly { get; }
属性值:对于所有数组,此属性始终返回false。
下面的程序说明了上面讨论的属性的用法:
范例1:
// C# program to illustrate
// IsReadOnly Property of
// Array class
using System;
namespace geeksforgeeks {
class GFG {
// Main Method
public static void Main()
{
// declares an 1D Array of string
string[] topic;
// assigning null to array
topic = new string[] { null };
// Here we check whether is
// array of fixed size or not
Console.WriteLine("Result: " + topic.IsReadOnly);
}
}
}
输出:
Result: False
范例2:
// C# program to illustrate
// IsReadOnly Property of
// Array class
using System;
namespace geeksforgeeks {
class GFG {
// Main Method
public static void Main()
{
// Two-dimensional array
int[, ] arr = new int[, ] {{1, 2},
{3, 4},
{5, 6},
{7, 8}};
// Here we check whether is
// array of fixed size or not
Console.WriteLine("Result: " + arr.IsReadOnly);
}
}
}
输出:
Result: False
笔记:
- Array实现了
IsReadOnly
属性,因为System.Collections.IList
接口需要它。 - 只读数组不允许在创建数组后添加,删除或修改元素。
- 如果用户需要只读集合,则他或她必须使用实现
System.Collections.IList
接口System.Collections
-
IList.IsReadOnly
转换或转换为IList接口对象,则IList.IsReadOnly属性将返回false 。但是,如果用户将数组IList
,则IsReadOnly属性将返回true。interface - 检索此属性的值是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.array.isreadonly?view=netframework-4.7.2