ReadOnlyCollectionBase 클래스

정의

제네릭이 아닌 강력한 형식의 읽기 전용 컬렉션의 abstract 기본 클래스를 제공합니다.

public ref class ReadOnlyCollectionBase abstract : System::Collections::ICollection
public abstract class ReadOnlyCollectionBase : System.Collections.ICollection
[System.Serializable]
public abstract class ReadOnlyCollectionBase : System.Collections.ICollection
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ReadOnlyCollectionBase : System.Collections.ICollection
type ReadOnlyCollectionBase = class
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
type ReadOnlyCollectionBase = class
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ReadOnlyCollectionBase = class
    interface ICollection
    interface IEnumerable
Public MustInherit Class ReadOnlyCollectionBase
Implements ICollection
상속
ReadOnlyCollectionBase
파생
특성
구현

예제

다음 코드 예제에서는 클래스를 ReadOnlyCollectionBase 구현합니다.

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.

*/
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.

*/
Imports System.Collections

Public Class ROCollection
    Inherits ReadOnlyCollectionBase


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


    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


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


    ' 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


    ' 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


    ' 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

End Class


'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.

설명

ReadOnlyCollectionBase 인스턴스는 항상 읽기 전용입니다. 이 클래스의 수정 가능한 버전을 참조 CollectionBase 하세요.

중요

새 개발에 클래스를 ReadOnlyCollectionBase 사용하지 않는 것이 좋습니다. 대신 제네릭 ReadOnlyCollection<T> 클래스를 사용하는 것이 좋습니다. 자세한 내용은 GitHub 사용할 수 없는 제네릭이 아닌 컬렉션을 참조하세요.

구현자 참고

이 기본 클래스는 구현자가 강력한 형식의 읽기 전용 사용자 지정 컬렉션을 쉽게 만들 수 있도록 하기 위해 제공됩니다. 구현자는 자체 클래스를 만드는 대신 이 기본 클래스를 확장하는 것이 좋습니다. 이 기본 클래스의 멤버는 보호되며 파생 클래스를 통해서만 사용됩니다.

이 클래스는 속성을 통해 InnerList 기본 컬렉션을 사용할 수 있도록 합니다. 이 속성은 직접 파생된 클래스에서 ReadOnlyCollectionBase만 사용할 수 있습니다. 파생 클래스는 자체 사용자가 기본 컬렉션을 수정할 수 없도록 해야 합니다.

생성자

ReadOnlyCollectionBase()

ReadOnlyCollectionBase 클래스의 새 인스턴스를 초기화합니다.

속성

Count

ReadOnlyCollectionBase 인스턴스에 포함된 요소 수를 가져옵니다.

InnerList

ReadOnlyCollectionBase 인스턴스에 포함된 요소의 목록을 가져옵니다.

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetEnumerator()

ReadOnlyCollectionBase 인스턴스를 반복하는 열거자를 반환합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

명시적 인터페이스 구현

ICollection.CopyTo(Array, Int32)

대상 배열의 지정된 인덱스에서 시작하여 전체 ReadOnlyCollectionBase을 호환되는 1차원 Array에 복사합니다.

ICollection.IsSynchronized

ReadOnlyCollectionBase 개체에 대한 액세스가 동기화되어 스레드로부터 안전하게 보호되는지 여부를 나타내는 값을 가져옵니다.

ICollection.SyncRoot

ReadOnlyCollectionBase 개체에 대한 액세스를 동기화하는 데 사용할 수 있는 개체를 가져옵니다.

확장 메서드

Cast<TResult>(IEnumerable)

IEnumerable의 요소를 지정된 형식으로 캐스팅합니다.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable의 요소를 필터링합니다.

AsParallel(IEnumerable)

쿼리를 병렬화할 수 있도록 합니다.

AsQueryable(IEnumerable)

IEnumerableIQueryable로 변환합니다.

적용 대상

스레드 보안

공용 정적 (Shared Visual Basic의)이 형식의 멤버는 스레드로부터 안전 합니다. 인스턴스 구성원은 스레드로부터의 안전성이 보장되지 않습니다.

이 구현은 동기화된(스레드로부터 안전한) 래퍼를 ReadOnlyCollectionBase제공하지 않지만 파생 클래스는 속성을 사용하여 SyncRoot 자체 동기화된 버전을 ReadOnlyCollectionBase 만들 수 있습니다.

컬렉션 전체를 열거하는 프로시저는 기본적으로 스레드로부터 안전하지 않습니다. 컬렉션이 동기화되어 있을 때 다른 스레드에서 해당 컬렉션을 수정할 수 있으므로 이렇게 되면 열거자에서 예외가 throw됩니다. 열거하는 동안 스레드로부터 안전을 보장하려면 전체 열거를 수행하는 동안 컬렉션을 잠그거나 다른 스레드에서 변경된 내용으로 인해 발생한 예외를 catch하면 됩니다.

추가 정보