List
句法:
public System.Collections.ObjectModel.ReadOnlyCollection AsReadOnly ();
返回值:返回一个对象,该对象充当当前List
例子:
// C# code to create a read-only
// wrapper for the List
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating an List of Integers
List firstlist = new List();
// Adding elements to List
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
firstlist.Add(5);
firstlist.Add(6);
firstlist.Add(7);
Console.WriteLine("Before Wrapping: ");
// Displaying the elements in the List
foreach(int i in firstlist)
{
Console.WriteLine(i);
}
// Creating a Read-Only packing
// around the List
IList mylist2 = firstlist.AsReadOnly();
Console.WriteLine("After Wrapping: ");
// Displaying the elements
foreach(int m in mylist2)
{
Console.WriteLine(m);
}
Console.WriteLine("Trying to add new element into mylist2:");
// it will give error
mylist2.Add(8);
}
}
输出:
Before Wrapping:
1
2
3
4
5
6
7
After Wrapping:
1
2
3
4
5
6
7
Trying to add new element into mylist2:
运行时错误:
Unhandled Exception:
System.NotSupportedException: Collection is read-only.
笔记:
- 只读的集合只是一个带有包装器的集合,该包装器可防止修改该集合。如果对基础集合进行了更改,则只读集合将反映这些更改。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.asreadonly?view=netframework-4.7.2