ArrayList.ReadOnly(ArrayList)方法用于获取只读ArrayList包装器。
句法:
public static System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list);
在此,列表是要包装的ArrayList。
返回值:返回列表周围的只读ArrayList包装器。
异常:如果列表为null,则此方法返回ArgumentNullException。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to create a read-only
// wrapper for the ArrayList
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating an ArrayList
ArrayList myList = new ArrayList();
// Adding elements to ArrayList
myList.Add("Geeks");
myList.Add("for");
myList.Add("Geeks");
myList.Add("Noida");
myList.Add("Geeks Classes");
myList.Add("Delhi");
// Creating a Read-Only packing
// around the ArrayList
ArrayList myList2 = ArrayList.ReadOnly(myList);
// --------- Using IsReadOnly Property
// print the status of both ArrayList
Console.WriteLine("myList ArrayList is {0}.",
myList.IsReadOnly ? "read-only" :
"not read-only");
Console.WriteLine("myList2 ArrayList is {0}.",
myList2.IsReadOnly ? "read-only" :
"not read-only");
}
}
输出:
myList ArrayList is not read-only.
myList2 ArrayList is read-only.
范例2:
// C# code to create a read-only
// wrapper for the ArrayList
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating an ArrayList
ArrayList myList = new ArrayList();
// Adding elements to ArrayList
myList.Add("C");
myList.Add("C++");
myList.Add("Java");
myList.Add("C#");
myList.Add("Python");
Console.WriteLine("Before Wrapping: ");
// Displaying the elements in the ArrayList
foreach(string str in myList)
{
Console.WriteLine(str);
}
// Creating a Read-Only packing
// around the ArrayList
ArrayList myList2 = ArrayList.ReadOnly(myList);
Console.WriteLine("After Wrapping: ");
// Displaying the elements
foreach(string str in myList2)
{
Console.WriteLine(str);
}
Console.WriteLine("Trying to add new element into myList2:");
// it will give error
myList2.Add("HTML");
}
}
输出:
Before Wrapping:
C
C++
Java
C#
Python
After Wrapping:
C
C++
Java
C#
Python
Trying to add new element into myList2:
运行时错误:
Unhandled Exception:
System.NotSupportedException: Collection is read-only.
at System.Collections.ArrayList+ReadOnlyArrayList.Add
说明:在以上程序中,您可以从myList即原始ArrayList中添加或删除元素,这些元素将反映到只读集合中。
笔记:
- 为了防止对list进行任何修改,请仅通过此包装器公开list。
- 只读的集合只是一个带有包装器的集合,该包装器可防止修改该集合。如果对基础集合进行了更改,则只读集合将反映这些更改。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.readonly?view=netframework-4.7.2#System_Collections_ArrayList_ReadOnly_System_Collections_ArrayList_