ReadOnlyCollection<T> 类

定义

提供泛型只读集合的基类。Provides the base class for a generic read-only collection.

generic <typename T>
public ref class ReadOnlyCollection : System::Collections::Generic::ICollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IList<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::Generic::IReadOnlyList<T>, System::Collections::IList
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class ReadOnlyCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.IList
type ReadOnlyCollection<'T> = class
    interface IList<'T>
    interface IList
    interface IReadOnlyList<'T>
    interface ICollection<'T>
    interface seq<'T>
    interface IEnumerable
    interface ICollection
    interface IReadOnlyCollection<'T>
Public Class ReadOnlyCollection(Of T)
Implements ICollection(Of T), IEnumerable(Of T), IList, IList(Of T), IReadOnlyCollection(Of T), IReadOnlyList(Of T)

类型参数

T

集合中的元素类型。The type of elements in the collection.

继承
ReadOnlyCollection<T>
派生
属性
实现

示例

下面的代码示例演示了ReadOnlyCollection<T>类的多个成员。The following code example demonstrates several members of the ReadOnlyCollection<T> class. 此代码示例将创建List<T>一个字符串, 并向其添加四个恐龙名称。The code example creates a List<T> of strings and adds four dinosaur names to it. 然后, 该代码示例在中ReadOnlyCollection<T>包装列表。The code example then wraps the list in a ReadOnlyCollection<T>.

演示CountList<T> ReadOnlyCollection<T>ContainsItem[Int32]和成员IList.IndexOf后,代码List<T>示例显示, 只是将一个新项添加到并显示的内容ReadOnlyCollection<T>After demonstrating the Count, Contains, Item[Int32], and IList.IndexOf members, the code example shows that the ReadOnlyCollection<T> is just a wrapper for the original List<T> by adding a new item to the List<T> and displaying the contents of the ReadOnlyCollection<T>.

最后, 此代码示例创建一个大于集合的数组, 并使用CopyTo方法将集合的元素插入到数组的中间。Finally, the code example creates an array larger than the collection and uses the CopyTo method to insert the elements of the collection into the middle of the array.

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

void main()
{
    List<String^>^ dinosaurs = gcnew List<String^>();

    dinosaurs->Add("Tyrannosaurus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("Deinonychus");
    dinosaurs->Add("Compsognathus");

    ReadOnlyCollection<String^>^ readOnlyDinosaurs = 
        gcnew ReadOnlyCollection<String^>(dinosaurs);

    Console::WriteLine();
    for each(String^ dinosaur in readOnlyDinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nCount: {0}", readOnlyDinosaurs->Count);

    Console::WriteLine("\nContains(\"Deinonychus\"): {0}", 
        readOnlyDinosaurs->Contains("Deinonychus"));

    Console::WriteLine("\nreadOnlyDinosaurs[3]: {0}", 
        readOnlyDinosaurs[3]);

    Console::WriteLine("\nIndexOf(\"Compsognathus\"): {0}", 
        readOnlyDinosaurs->IndexOf("Compsognathus"));

    Console::WriteLine("\nInsert into the wrapped List:");
    Console::WriteLine("Insert(2, \"Oviraptor\")");
    dinosaurs->Insert(2, "Oviraptor");

    Console::WriteLine();
    for each( String^ dinosaur in readOnlyDinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    array<String^>^ dinoArray = 
        gcnew array<String^>(readOnlyDinosaurs->Count + 2);
    readOnlyDinosaurs->CopyTo(dinoArray, 1);

    Console::WriteLine("\nCopied array has {0} elements:", 
        dinoArray->Length);
    for each( String^ dinosaur in dinoArray )
    {
        Console::WriteLine("\"{0}\"", dinosaur);
    }
}

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Deinonychus
Compsognathus

Count: 4

Contains("Deinonychus"): True

readOnlyDinosaurs[3]: Compsognathus

IndexOf("Compsognathus"): 3

Insert into the wrapped List:
Insert(2, "Oviraptor")

Tyrannosaurus
Amargasaurus
Oviraptor
Deinonychus
Compsognathus

Copied array has 7 elements:
""
"Tyrannosaurus"
"Amargasaurus"
"Oviraptor"
"Deinonychus"
"Compsognathus"
""
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();

        dinosaurs.Add("Tyrannosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Compsognathus");

        ReadOnlyCollection<string> readOnlyDinosaurs = 
            new ReadOnlyCollection<string>(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in readOnlyDinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nCount: {0}", readOnlyDinosaurs.Count);

        Console.WriteLine("\nContains(\"Deinonychus\"): {0}", 
            readOnlyDinosaurs.Contains("Deinonychus"));

        Console.WriteLine("\nreadOnlyDinosaurs[3]: {0}", 
            readOnlyDinosaurs[3]);

        Console.WriteLine("\nIndexOf(\"Compsognathus\"): {0}", 
            readOnlyDinosaurs.IndexOf("Compsognathus"));

        Console.WriteLine("\nInsert into the wrapped List:");
        Console.WriteLine("Insert(2, \"Oviraptor\")");
        dinosaurs.Insert(2, "Oviraptor");

        Console.WriteLine();
        foreach( string dinosaur in readOnlyDinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        string[] dinoArray = new string[readOnlyDinosaurs.Count + 2];
        readOnlyDinosaurs.CopyTo(dinoArray, 1);

        Console.WriteLine("\nCopied array has {0} elements:", 
            dinoArray.Length);
        foreach( string dinosaur in dinoArray )
        {
            Console.WriteLine("\"{0}\"", dinosaur);
        }
    }
}

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Deinonychus
Compsognathus

Count: 4

Contains("Deinonychus"): True

readOnlyDinosaurs[3]: Compsognathus

IndexOf("Compsognathus"): 3

Insert into the wrapped List:
Insert(2, "Oviraptor")

Tyrannosaurus
Amargasaurus
Oviraptor
Deinonychus
Compsognathus

Copied array has 7 elements:
""
"Tyrannosaurus"
"Amargasaurus"
"Oviraptor"
"Deinonychus"
"Compsognathus"
""
 */
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of String)

        dinosaurs.Add("Tyrannosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Deinonychus")
        dinosaurs.Add("Compsognathus")

        Dim readOnlyDinosaurs As _
            New ReadOnlyCollection(Of String)(dinosaurs)

        Console.WriteLine()
        For Each dinosaur As String In readOnlyDinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Count: {0}", _
            readOnlyDinosaurs.Count)

        Console.WriteLine(vbLf & "Contains(""Deinonychus""): {0}", _
            readOnlyDinosaurs.Contains("Deinonychus"))

        Console.WriteLine(vbLf & _
            "readOnlyDinosaurs(3): {0}", readOnlyDinosaurs(3))

        Console.WriteLine(vbLf & "IndexOf(""Compsognathus""): {0}", _
            readOnlyDinosaurs.IndexOf("Compsognathus"))

        Console.WriteLine(vbLf & "Insert into the wrapped List:")
        Console.WriteLine("Insert(2, ""Oviraptor"")")
        dinosaurs.Insert(2, "Oviraptor")

        Console.WriteLine()
        For Each dinosaur As String In readOnlyDinosaurs
            Console.WriteLine(dinosaur)
        Next

        Dim dinoArray(readOnlyDinosaurs.Count + 1) As String
        readOnlyDinosaurs.CopyTo(dinoArray, 1)

        Console.WriteLine(vbLf & "Copied array has {0} elements:", _
            dinoArray.Length)
        For Each dinosaur As String In dinoArray
            Console.WriteLine("""{0}""", dinosaur)
        Next

   End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Deinonychus
'Compsognathus
'
'Count: 4
'
'Contains("Deinonychus"): True
'
'readOnlyDinosaurs(3): Compsognathus
'
'IndexOf("Compsognathus"): 3
'
'Insert into the wrapped List:
'Insert(2, "Oviraptor")
'
'Tyrannosaurus
'Amargasaurus
'Oviraptor
'Deinonychus
'Compsognathus
'
'Copied array has 7 elements:
'""
'"Tyrannosaurus"
'"Amargasaurus"
'"Oviraptor"
'"Deinonychus"
'"Compsognathus"
'""

注解

ReadOnlyCollection<T>泛型类的实例始终是只读的。An instance of the ReadOnlyCollection<T> generic class is always read-only. 只读集合就是一个集合, 其中包含阻止修改集合的包装器;因此, 如果对基础集合进行了更改, 只读集合将反映这些更改。A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes. 有关Collection<T>此类的可修改版本, 请参阅。See Collection<T> for a modifiable version of this class.

继承者说明

提供此基类是为了使实现者可以更轻松地创建泛型的只读自定义集合。This base class is provided to make it easier for implementers to create a generic read-only custom collection. 鼓励实现者扩展此基类, 而不是自行创建。Implementers are encouraged to extend this base class instead of creating their own.

构造函数

ReadOnlyCollection<T>(IList<T>)

初始化 ReadOnlyCollection<T> 类的新实例,该实例是指定列表周围的只读包装。Initializes a new instance of the ReadOnlyCollection<T> class that is a read-only wrapper around the specified list.

属性

Count

获取包含在 ReadOnlyCollection<T> 实例中的元素数。Gets the number of elements contained in the ReadOnlyCollection<T> instance.

Item[Int32]

获取指定索引处的元素。Gets the element at the specified index.

Items

返回 IList<T> 包装的 ReadOnlyCollection<T>Returns the IList<T> that the ReadOnlyCollection<T> wraps.

方法

Contains(T)

确定某元素是否在 ReadOnlyCollection<T> 中。Determines whether an element is in the ReadOnlyCollection<T>.

CopyTo(T[], Int32)

从目标数组的指定索引处开始将整个 ReadOnlyCollection<T> 复制到兼容的一维 ArrayCopies the entire ReadOnlyCollection<T> to a compatible one-dimensional Array, starting at the specified index of the target array.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEnumerator()

返回循环访问 ReadOnlyCollection<T> 的枚举数。Returns an enumerator that iterates through the ReadOnlyCollection<T>.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
IndexOf(T)

搜索指定的对象,并返回整个 ReadOnlyCollection<T> 中第一个匹配项的从零开始的索引。Searches for the specified object and returns the zero-based index of the first occurrence within the entire ReadOnlyCollection<T>.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

显式界面实现

ICollection.CopyTo(Array, Int32)

从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。Gets an object that can be used to synchronize access to the ICollection.

ICollection<T>.Add(T)

将某项添加到 ICollection<T> 中。Adds an item to the ICollection<T>. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

ICollection<T>.Clear()

ICollection<T> 中移除所有项。Removes all items from the ICollection<T>. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

ICollection<T>.IsReadOnly

获取一个值,该值指示 ICollection<T> 是否为只读。Gets a value indicating whether the ICollection<T> is read-only.

ICollection<T>.Remove(T)

ICollection<T> 中移除特定对象的第一个匹配项。Removes the first occurrence of a specific object from the ICollection<T>. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IEnumerable.GetEnumerator()

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

IList.Add(Object)

将某项添加到 IList 中。Adds an item to the IList. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IList.Clear()

IList 中移除所有项。Removes all items from the IList. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IList.Contains(Object)

确定 IList 是否包含特定值。Determines whether the IList contains a specific value.

IList.IndexOf(Object)

确定 IList 中特定项的索引。Determines the index of a specific item in the IList.

IList.Insert(Int32, Object)

IList 中的指定索引处插入一个项。Inserts an item to the IList at the specified index. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IList.IsFixedSize

获取一个值,该值指示 IList 是否具有固定大小。Gets a value indicating whether the IList has a fixed size.

IList.IsReadOnly

获取一个值,该值指示 IList 是否为只读。Gets a value indicating whether the IList is read-only.

IList.Item[Int32]

获取指定索引处的元素。Gets the element at the specified index. 如果尝试设置指定索引处的项,则会发生 NotSupportedExceptionA NotSupportedException occurs if you try to set the item at the specified index.

IList.Remove(Object)

IList 中移除特定对象的第一个匹配项。Removes the first occurrence of a specific object from the IList. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IList.RemoveAt(Int32)

移除位于指定索引处的 IList 项。Removes the IList item at the specified index. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IList<T>.Insert(Int32, T)

IList<T> 中的指定索引处插入一个项。Inserts an item to the IList<T> at the specified index. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

IList<T>.Item[Int32]

获取指定索引处的元素。Gets the element at the specified index. 如果您尝试设置指定索引处的项,则会发生 NotSupportedExceptionAn NotSupportedException occurs if you try to set the item at the specified index.

IList<T>.RemoveAt(Int32)

移除位于指定索引处的 IList<T> 项。Removes the IList<T> item at the specified index. 此实现始终引发 NotSupportedExceptionThis implementation always throws NotSupportedException.

扩展方法

CopyToDataTable<T>(IEnumerable<T>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 IEnumerable<T> 对象副本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个节点的上级。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个节点的上级。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子代节点的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>)

返回源集合中每个元素和文档的子元素的集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName)

返回源集合中经过筛选的每个元素和文档的子元素集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>)

返回节点集合(其中包含源集合中的所有节点),并按文档顺序排列。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子节点集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>)

将源集合中的每个节点从其父节点中移除。Removes every node in the source collection from its parent node.

适用于

线程安全性

此类型的Shared公共静态 (在 Visual Basic) 成员是线程安全的。Public static (Shared in Visual Basic) members of this type are thread safe. 但不保证所有实例成员都是线程安全的。Any instance members are not guaranteed to be thread safe.

只要不修改集合,就可以同时支持多个读取器。ReadOnlyCollection<T>A ReadOnlyCollection<T> can support multiple readers concurrently, as long as the collection is not modified. 尽管如此, 枚举集合本身并不是一个线程安全的过程。Even so, enumerating through a collection is intrinsically not a thread-safe procedure. 若要确保枚举过程中的线程安全性,可以在整个枚举过程中锁定集合。To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

另请参阅