ReadOnlyCollectionBase 类

为强类型非泛型只读集合提供 abstract 基类。

**命名空间:**System.Collections
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public MustInherit Class ReadOnlyCollectionBase
    Implements ICollection, IEnumerable
用法
Dim instance As ReadOnlyCollectionBase
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public abstract class ReadOnlyCollectionBase : ICollection, IEnumerable
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class ReadOnlyCollectionBase abstract : ICollection, IEnumerable
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public abstract class ReadOnlyCollectionBase implements ICollection, IEnumerable
SerializableAttribute 
ComVisibleAttribute(true) 
public abstract class ReadOnlyCollectionBase implements ICollection, IEnumerable

备注

ReadOnlyCollectionBase 实例始终是只读的。有关此类的可修改版本,请参见 CollectionBase

给实现者的说明 提供此基类旨在使实施者创建强类型只读自定义集合变得更容易。实现者最好扩展此基类,而不是创建自己的类。此基类的成员受保护并且只能通过派生类使用。 此类通过 InnerList 属性使基础集合可用;该属性只能被直接派生自 ReadOnlyCollectionBase 的类使用。该派生类必须确保自己的用户不能修改基础集合。

示例

下面的代码示例实现 ReadOnlyCollectionBase 类。

Imports System
Imports System.Collections

Public Class ROCollection
    Inherits ReadOnlyCollectionBase


    Public Sub New(sourceList As IList)
        InnerList.AddRange(sourceList)
    End Sub 'New


    Default Public ReadOnly Property Item(index As Integer) As [Object]
        Get
            Return InnerList(index)
        End Get
    End Property


    Public Function IndexOf(value As [Object]) As Integer
        Return InnerList.IndexOf(value)
    End Function 'IndexOf


    Public Function Contains(value As [Object]) As Boolean
        Return InnerList.Contains(value)
    End Function 'Contains

End Class 'ROCollection 


Public Class SamplesCollectionBase

    Public Shared Sub Main()

        ' Create an ArrayList.
        Dim myAL As New ArrayList()
        myAL.Add("red")
        myAL.Add("blue")
        myAL.Add("yellow")
        myAL.Add("green")
        myAL.Add("orange")
        myAL.Add("purple")

        ' Create a new ROCollection that contains the elements in myAL.
        Dim myCol As New ROCollection(myAL)

        ' Display the contents of the collection using For Each. This is the preferred method.
        Console.WriteLine("Contents of the collection (using For Each):")
        PrintValues1(myCol)

        ' Display the contents of the collection using the enumerator.
        Console.WriteLine("Contents of the collection (using enumerator):")
        PrintValues2(myCol)

        ' Display the contents of the collection using the Count property and the Item property.
        Console.WriteLine("Contents of the collection (using Count and Item):")
        PrintIndexAndValues(myCol)

        ' Search the collection with Contains and IndexOf.
        Console.WriteLine("Contains yellow: {0}", myCol.Contains("yellow"))
        Console.WriteLine("orange is at index {0}.", myCol.IndexOf("orange"))
        Console.WriteLine()

    End Sub 'Main


    ' Uses the Count property and the Item property.
    Public Shared Sub PrintIndexAndValues(myCol As ROCollection)
        Dim i As Integer
        For i = 0 To myCol.Count - 1
            Console.WriteLine("   [{0}]:   {1}", i, myCol(i))
        Next i
        Console.WriteLine()
    End Sub 'PrintIndexAndValues


    ' Uses the For Each statement which hides the complexity of the enumerator.
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues1(myCol As ROCollection)
        Dim obj As [Object]
        For Each obj In  myCol
            Console.WriteLine("   {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub 'PrintValues1


    ' Uses the enumerator. 
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues2(myCol As ROCollection)
        Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
        While myEnumerator.MoveNext()
            Console.WriteLine("   {0}", myEnumerator.Current)
        End While
        Console.WriteLine()
    End Sub 'PrintValues2

End Class 'SamplesCollectionBase 


'This code produces the following output.
'
'Contents of the collection (using For Each):
'   red
'   blue
'   yellow
'   green
'   orange
'   purple
'
'Contents of the collection (using enumerator):
'   red
'   blue
'   yellow
'   green
'   orange
'   purple
'
'Contents of the collection (using Count and Item):
'   [0]:   red
'   [1]:   blue
'   [2]:   yellow
'   [3]:   green
'   [4]:   orange
'   [5]:   purple
'
'Contains yellow: True
'orange is at index 4.
using System;
using System.Collections;

public class ROCollection : ReadOnlyCollectionBase  {

   public ROCollection( IList sourceList )  {
      InnerList.AddRange( sourceList );
   }

   public Object this[ int index ]  {
      get  {
         return( InnerList[index] );
      }
   }

   public int IndexOf( Object value )  {
      return( InnerList.IndexOf( value ) );
   }

   public bool Contains( Object value )  {
      return( InnerList.Contains( value ) );
   }

}


public class SamplesCollectionBase  {

   public static void Main()  {

      // Create an ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add( "red" );
      myAL.Add( "blue" );
      myAL.Add( "yellow" );
      myAL.Add( "green" );
      myAL.Add( "orange" );
      myAL.Add( "purple" );
 
      // Create a new ROCollection that contains the elements in myAL.
      ROCollection myCol = new ROCollection( myAL );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Contents of the collection (using foreach):" );
      PrintValues1( myCol );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Contents of the collection (using enumerator):" );
      PrintValues2( myCol );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Contents of the collection (using Count and Item):" );
      PrintIndexAndValues( myCol );

      // Search the collection with Contains and IndexOf.
      Console.WriteLine( "Contains yellow: {0}", myCol.Contains( "yellow" ) );
      Console.WriteLine( "orange is at index {0}.", myCol.IndexOf( "orange" ) );
      Console.WriteLine();

   }
 
   // Uses the Count property and the Item property.
   public static void PrintIndexAndValues( ROCollection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   [{0}]:   {1}", i, myCol[i] );
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues1( ROCollection myCol )  {
      foreach ( Object obj in myCol )
         Console.WriteLine( "   {0}", obj );
      Console.WriteLine();
   }

   // Uses the enumerator. 
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues2( ROCollection myCol )  {
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0}", myEnumerator.Current );
      Console.WriteLine();
   }

}


/* 
This code produces the following output.

Contents of the collection (using foreach):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using enumerator):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using Count and Item):
   [0]:   red
   [1]:   blue
   [2]:   yellow
   [3]:   green
   [4]:   orange
   [5]:   purple

Contains yellow: True
orange is at index 4.

*/
using namespace System;
using namespace System::Collections;
public ref class ROCollection: public ReadOnlyCollectionBase
{
public:
   ROCollection( IList^ sourceList )
   {
      InnerList->AddRange( sourceList );
   }

   property Object^ Item [int]
   {
      Object^ get( int index )
      {
         return (InnerList[ index ]);
      }

   }
   int IndexOf( Object^ value )
   {
      return (InnerList->IndexOf( value ));
   }

   bool Contains( Object^ value )
   {
      return (InnerList->Contains( value ));
   }

};

void PrintIndexAndValues( ROCollection^ myCol );
void PrintValues2( ROCollection^ myCol );
int main()
{
   // Create an ArrayList.
   ArrayList^ myAL = gcnew ArrayList;
   myAL->Add( "red" );
   myAL->Add( "blue" );
   myAL->Add( "yellow" );
   myAL->Add( "green" );
   myAL->Add( "orange" );
   myAL->Add( "purple" );

   // Create a new ROCollection that contains the elements in myAL.
   ROCollection^ myCol = gcnew ROCollection( myAL );

   // Display the contents of the collection using the enumerator.
   Console::WriteLine( "Contents of the collection (using enumerator):" );
   PrintValues2( myCol );

   // Display the contents of the collection using the Count property and the Item property.
   Console::WriteLine( "Contents of the collection (using Count and Item):" );
   PrintIndexAndValues( myCol );

   // Search the collection with Contains and IndexOf.
   Console::WriteLine( "Contains yellow: {0}", myCol->Contains( "yellow" ) );
   Console::WriteLine( "orange is at index {0}.", myCol->IndexOf( "orange" ) );
   Console::WriteLine();
}


// Uses the Count property and the Item property.
void PrintIndexAndValues( ROCollection^ myCol )
{
   for ( int i = 0; i < myCol->Count; i++ )
      Console::WriteLine( "   [{0}]:   {1}", i, myCol->Item[ i ] );
   Console::WriteLine();
}


// Uses the enumerator. 
void PrintValues2( ROCollection^ myCol )
{
   System::Collections::IEnumerator^ myEnumerator = myCol->GetEnumerator();
   while ( myEnumerator->MoveNext() )
      Console::WriteLine( "   {0}", myEnumerator->Current );

   Console::WriteLine();
}

/* 
This code produces the following output.

Contents of the collection (using enumerator):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using Count and Item):
   [0]:   red
   [1]:   blue
   [2]:   yellow
   [3]:   green
   [4]:   orange
   [5]:   purple

Contains yellow: True
orange is at index 4.

*/
import System.*;
import System.Collections.*;

public class ROCollection extends ReadOnlyCollectionBase
{
    public ROCollection(IList sourceList) 
    {
        get_InnerList().AddRange(sourceList);
    } //ROCollection
   
    /** @property 
     */
    public Object get_Item(int index)
    {
        return get_InnerList().get_Item(index);
    } //get_Item
     
    public int IndexOf(Object value) 
    {
        return get_InnerList().IndexOf(value);
    } //IndexOf
   
    public boolean Contains(Object value) 
    {
        return get_InnerList().Contains(value);
    } //Contains
} //ROCollection

public class SamplesCollectionBase
{
    public static void main(String[] args)
    {
        // Create an ArrayList.
        ArrayList myAL = new ArrayList();
        myAL.Add("red");
        myAL.Add("blue");
        myAL.Add("yellow");
        myAL.Add("green");
        myAL.Add("orange");
        myAL.Add("purple");
          
        // Create a new ROCollection that contains the elements in myAL.
        ROCollection myCol = new ROCollection(myAL);
          
        // Display the contents of the collection using for. This is the 
        // preferred method.
        Console.WriteLine("Contents of the collection (using for):");
        PrintValues1(myCol);
          
        // Display the contents of the collection using the enumerator.
        Console.WriteLine("Contents of the collection (using enumerator):");
        PrintValues2(myCol);
          
        // Display the contents of the collection using the Count property and 
        // the Item property.
        Console.WriteLine("Contents of the collection (using Count and Item):");
        PrintIndexAndValues(myCol);
          
        // Search the collection with Contains and IndexOf.
        Console.WriteLine("Contains yellow: {0}",
            (System.Boolean)myCol.Contains("yellow"));
        Console.WriteLine("orange is at index {0}.", 
            (Int32)myCol.IndexOf("orange"));
        Console.WriteLine();
    } //main
    
    // Uses the Count property and the Item property.
    public static void PrintIndexAndValues(ROCollection myCol) 
    {
        for(int i = 0; i < myCol.get_Count(); i++) {
            Console.WriteLine("   [{0}]:   {1}",(Int32)i, myCol.get_Item(i));
        } 
        Console.WriteLine();
    } //PrintIndexAndValues
   
    // Uses the for statement which hides the complexity of the enumerator.
    // NOTE: The for statement is the preferred way of enumerating the contents
    // of a collection.
    public static void PrintValues1(ROCollection myCol) 
    {
        for (int iCtr = 0; iCtr < myCol.get_Count(); iCtr++ ) {
            Object obj = myCol.get_Item(iCtr);
            Console.WriteLine("   {0}", obj);
        }
        Console.WriteLine();
    } //PrintValues1
     
    // Uses the enumerator. 
    // NOTE: The for statement is the preferred way of enumerating the
    // contents of a collection.
    public static void PrintValues2(ROCollection myCol) 
    {
        System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
        while(myEnumerator.MoveNext()) {
            Console.WriteLine("   {0}", myEnumerator.get_Current());
        }
        Console.WriteLine();
    } //PrintValues2
} //SamplesCollectionBase
 
/* 
This code produces the following output.

Contents of the collection (using for):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using enumerator):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using Count and Item):
   [0]:   red
   [1]:   blue
   [2]:   yellow
   [3]:   green
   [4]:   orange
   [5]:   purple

Contains yellow: True
orange is at index 4.

*/

继承层次结构

System.Object
  System.Collections.ReadOnlyCollectionBase
     派生类

线程安全

此类型的公共静态(在 Visual Basic 中为 Shared)成员是线程安全的。但不能保证任何实例成员是线程安全的。

此实现不为 ReadOnlyCollectionBase 提供同步(线程安全)包装,但派生类可使用 SyncRoot 属性创建它们自己的 ReadOnlyCollectionBase 同步版本。

通过集合枚举在本质上不是一个线程安全的过程。即使一个集合已进行同步,其他线程仍可以修改该集合,这将导致枚举数引发异常。若要在枚举过程中保证线程安全,可以在整个枚举过程中锁定集合,或者捕捉由于其他线程进行的更改而引发的异常。

平台

Windows 98、Windows 2000 SP4、Windows Millennium Edition、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

ReadOnlyCollectionBase 成员
System.Collections 命名空间
ArrayList 类
CollectionBase 类
System.Collections.Generic