次の方法で共有


NameObjectCollectionBase クラス

関連付けられた String キーおよび Object 値のコレクションの抽象 (Visual Basic では MustInherit) 基本クラスを提供します。これらのキーおよび値には、キーまたはインデックスのいずれかを使用してアクセスできます。

この型のすべてのメンバの一覧については、NameObjectCollectionBase メンバ を参照してください。

System.Object
   System.Collections.Specialized.NameObjectCollectionBase
      派生クラス

<Serializable>
MustInherit Public Class NameObjectCollectionBase   Implements ICollection, IEnumerable, ISerializable, _   IDeserializationCallback
[C#]
[Serializable]
public abstract class NameObjectCollectionBase : ICollection,   IEnumerable, ISerializable, IDeserializationCallback
[C++]
[Serializable]
public __gc __abstract class NameObjectCollectionBase : public   ICollection, IEnumerable, ISerializable,   IDeserializationCallback
[JScript]
public
   Serializable
abstract class NameObjectCollectionBase implements   ICollection, IEnumerable, ISerializable,   IDeserializationCallback

スレッドセーフ

この型の public static (Visual Basic では Shared) メンバは、マルチスレッド操作に対して安全です。インスタンス メンバがスレッド セーフになるかどうかは保証されていません。

この実装は、 NameObjectCollectionBase 用の同期された (スレッド セーフな) ラッパーは提供しませんが、派生クラスでは、 SyncRoot プロパティを使用して、同期した NameObjectCollectionBase を独自に作成できます。

コレクションの列挙処理は、本質的にはスレッド セーフな処理ではありません。コレクションが同期されている場合でも、他のスレッドがそのコレクションを変更する可能性はあり、そのような状況が発生すると列挙子は例外をスローします。列挙処理を確実にスレッド セーフに行うには、列挙中にコレクションをロックするか、他のスレッドによって行われた変更によってスローされる例外をキャッチします。

解説

このクラスの基になる構造体はハッシュ テーブルです。

容量は、 NameObjectCollectionBase インスタンスが格納できるキーと値の組み合わせの数になります。既定の初期量は 0 です。この容量は必要に応じて自動的に増加します。

ハッシュ コード プロバイダは、キーに対するハッシュ コードを NameObjectCollectionBase インスタンスに提供します。既定のハッシュ コード プロバイダは CaseInsensitiveHashCodeProvider です。

比較演算子は 2 つのキーが等しいかどうかを判断します。既定の比較演算子は CaseInsensitiveComparer です。

.NET Framework Version 1.0 の場合、このクラスはカルチャに依存した文字列比較を使用します。ただし、.NET Framework Version 1.1 以降の場合、このクラスは文字列を比較するときに CultureInfo.InvariantCulture を使用します。カルチャが比較と並べ替えに与える影響の詳細については、「 固有カルチャのデータの比較と並べ替え 」および「 カルチャを認識しない文字列操作の実行 」を参照してください。

キーまたは値として null 参照 (Visual Basic では Nothing) を使用できます。

注意    BaseGet メソッドでは、指定したキーが見つからないために返される null 参照 (Nothing) と、キーに関連付けられている値が null 参照 (Nothing) であるために返される null 参照 (Nothing) とが区別されません。

使用例

[Visual Basic, C#, C++] NameObjectCollectionBase クラスを実装および使用する方法については、次のコード例を参照してください。

 
Imports System
Imports System.Collections
Imports System.Collections.Specialized

Public Class MyCollection
   Inherits NameObjectCollectionBase

   Private _de As New DictionaryEntry()

   ' Creates an empty collection.
   Public Sub New()
   End Sub 'New

   ' Adds elements from an IDictionary into the new collection.
   Public Sub New(d As IDictionary, bReadOnly As [Boolean])
      Dim de As DictionaryEntry
      For Each de In  d
         Me.BaseAdd(CType(de.Key, [String]), de.Value)
      Next de
      Me.IsReadOnly = bReadOnly
   End Sub 'New

   ' Gets a key-and-value pair (DictionaryEntry) using an index.
   Default Public ReadOnly Property Item(index As Integer) As DictionaryEntry
      Get
         _de.Key = Me.BaseGetKey(index)
         _de.Value = Me.BaseGet(index)
         Return _de
      End Get
   End Property

   ' Gets or sets the value associated with the specified key.
   Default Public Property Item(key As [String]) As [Object]
      Get
         Return Me.BaseGet(key)
      End Get
      Set
         Me.BaseSet(key, value)
      End Set
   End Property

   ' Gets a String array that contains all the keys in the collection.
   Public ReadOnly Property AllKeys() As [String]()
      Get
         Return Me.BaseGetAllKeys()
      End Get
   End Property

   ' Gets an Object array that contains all the values in the collection.
   Public ReadOnly Property AllValues() As Array
      Get
         Return Me.BaseGetAllValues()
      End Get
   End Property

   ' Gets a String array that contains all the values in the collection.
   Public ReadOnly Property AllStringValues() As [String]()
      Get
         Return CType(Me.BaseGetAllValues(Type.GetType("System.String")), [String]())
      End Get
   End Property

   ' Gets a value indicating if the collection contains keys that are not null.
   Public ReadOnly Property HasKeys() As [Boolean]
      Get
         Return Me.BaseHasKeys()
      End Get
   End Property

   ' Adds an entry to the collection.
   Public Sub Add(key As [String], value As [Object])
      Me.BaseAdd(key, value)
   End Sub 'Add

   ' Removes an entry with the specified key from the collection.
   Overloads Public Sub Remove(key As [String])
      Me.BaseRemove(key)
   End Sub 'Remove

   ' Removes an entry in the specified index from the collection.
   Overloads Public Sub Remove(index As Integer)
      Me.BaseRemoveAt(index)
   End Sub 'Remove

   ' Clears all the elements in the collection.
   Public Sub Clear()
      Me.BaseClear()
   End Sub 'Clear

End Class 'MyCollection


Public Class SamplesNameObjectCollectionBase   

   Public Shared Sub Main()

      ' Creates and initializes a new MyCollection that is read-only.
      Dim d = New ListDictionary()
      d.Add("red", "apple")
      d.Add("yellow", "banana")
      d.Add("green", "pear")
      Dim myROCol As New MyCollection(d, True)

      ' Tries to add a new item.
      Try
         myROCol.Add("blue", "sky")
      Catch e As NotSupportedException
         Console.WriteLine(e.ToString())
      End Try

      ' Displays the keys and values of the MyCollection.
      Console.WriteLine("Read-Only Collection:")
      PrintKeysAndValues(myROCol)

      ' Creates and initializes an empty MyCollection that is writable.
      Dim myRWCol As New MyCollection()

      ' Adds new items to the collection.
      myRWCol.Add("purple", "grape")
      myRWCol.Add("orange", "tangerine")
      myRWCol.Add("black", "berries")
      Console.WriteLine("Writable Collection (after adding values):")
      PrintKeysAndValues(myRWCol)

      ' Changes the value of one element.
      myRWCol("orange") = "grapefruit"
      Console.WriteLine("Writable Collection (after changing one value):")
      PrintKeysAndValues(myRWCol)

      ' Removes one item from the collection.
      myRWCol.Remove("black")
      Console.WriteLine("Writable Collection (after removing one value):")
      PrintKeysAndValues(myRWCol)

      ' Removes all elements from the collection.
      myRWCol.Clear()
      Console.WriteLine("Writable Collection (after clearing the collection):")
      PrintKeysAndValues(myRWCol)

   End Sub 'Main

   ' Prints the indexes, keys, and values.
   Public Shared Sub PrintKeysAndValues(myCol As MyCollection)
      Dim i As Integer
      For i = 0 To myCol.Count - 1
         Console.WriteLine("[{0}] : {1}, {2}", i, myCol(i).Key, myCol(i).Value)
      Next i
   End Sub 'PrintKeysAndValues

   ' Prints the keys and values using AllKeys.
   Public Shared Sub PrintKeysAndValues2(myCol As MyCollection)
      Dim s As [String]
      For Each s In  myCol.AllKeys
         Console.WriteLine("{0}, {1}", s, myCol(s))
      Next s
   End Sub 'PrintKeysAndValues2

End Class 'SamplesNameObjectCollectionBase


'This code produces the following output.
'
'System.NotSupportedException: Collection is read-only.
'   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
'   at SamplesNameObjectCollectionBase.Main()
'Read-Only Collection:
'[0] : red, apple
'[1] : yellow, banana
'[2] : green, pear
'Writable Collection (after adding values):
'[0] : purple, grape
'[1] : orange, tangerine
'[2] : black, berries
'Writable Collection (after changing one value):
'[0] : purple, grape
'[1] : orange, grapefruit
'[2] : black, berries
'Writable Collection (after removing one value):
'[0] : purple, grape
'[1] : orange, grapefruit
'Writable Collection (after clearing the collection):


[C#] 
using System;
using System.Collections;
using System.Collections.Specialized;

public class MyCollection : NameObjectCollectionBase  {

   private DictionaryEntry _de = new DictionaryEntry();

   // Creates an empty collection.
   public MyCollection()  {
   }

   // Adds elements from an IDictionary into the new collection.
   public MyCollection( IDictionary d, Boolean bReadOnly )  {
      foreach ( DictionaryEntry de in d )  {
         this.BaseAdd( (String) de.Key, de.Value );
      }
      this.IsReadOnly = bReadOnly;
   }

   // Gets a key-and-value pair (DictionaryEntry) using an index.
   public DictionaryEntry this[ int index ]  {
      get  {
         _de.Key = this.BaseGetKey(index);
         _de.Value = this.BaseGet(index);
         return( _de );
      }
   }

   // Gets or sets the value associated with the specified key.
   public Object this[ String key ]  {
      get  {
         return( this.BaseGet( key ) );
      }
      set  {
         this.BaseSet( key, value );
      }
   }

   // Gets a String array that contains all the keys in the collection.
   public String[] AllKeys  {
      get  {
         return( this.BaseGetAllKeys() );
      }
   }

   // Gets an Object array that contains all the values in the collection.
   public Array AllValues  {
      get  {
         return( this.BaseGetAllValues() );
      }
   }

   // Gets a String array that contains all the values in the collection.
   public String[] AllStringValues  {
      get  {
         return( (String[]) this.BaseGetAllValues( Type.GetType( "System.String" ) ) );
      }
   }

   // Gets a value indicating if the collection contains keys that are not null.
   public Boolean HasKeys  {
      get  {
         return( this.BaseHasKeys() );
      }
   }

   // Adds an entry to the collection.
   public void Add( String key, Object value )  {
      this.BaseAdd( key, value );
   }

   // Removes an entry with the specified key from the collection.
   public void Remove( String key )  {
      this.BaseRemove( key );
   }

   // Removes an entry in the specified index from the collection.
   public void Remove( int index )  {
      this.BaseRemoveAt( index );
   }

   // Clears all the elements in the collection.
   public void Clear()  {
      this.BaseClear();
   }

}

public class SamplesNameObjectCollectionBase  {

   public static void Main()  {

      // Creates and initializes a new MyCollection that is read-only.
      IDictionary d = new ListDictionary();
      d.Add( "red", "apple" );
      d.Add( "yellow", "banana" );
      d.Add( "green", "pear" );
      MyCollection myROCol = new MyCollection( d, true );

      // Tries to add a new item.
      try  {
         myROCol.Add( "blue", "sky" );
      }
      catch ( NotSupportedException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Displays the keys and values of the MyCollection.
      Console.WriteLine( "Read-Only Collection:" );
      PrintKeysAndValues( myROCol );


      // Creates and initializes an empty MyCollection that is writable.
      MyCollection myRWCol = new MyCollection();

      // Adds new items to the collection.
      myRWCol.Add( "purple", "grape" );
      myRWCol.Add( "orange", "tangerine" );
      myRWCol.Add( "black", "berries" );
      Console.WriteLine( "Writable Collection (after adding values):" );
      PrintKeysAndValues( myRWCol );

      // Changes the value of one element.
      myRWCol["orange"] = "grapefruit";
      Console.WriteLine( "Writable Collection (after changing one value):" );
      PrintKeysAndValues( myRWCol );

      // Removes one item from the collection.
      myRWCol.Remove( "black" );
      Console.WriteLine( "Writable Collection (after removing one value):" );
      PrintKeysAndValues( myRWCol );

      // Removes all elements from the collection.
      myRWCol.Clear();
      Console.WriteLine( "Writable Collection (after clearing the collection):" );
      PrintKeysAndValues( myRWCol );

   }

   // Prints the indexes, keys, and values.
   public static void PrintKeysAndValues( MyCollection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )  {
         Console.WriteLine( "[{0}] : {1}, {2}", i, myCol[i].Key, myCol[i].Value );
      }
   }

   // Prints the keys and values using AllKeys.
   public static void PrintKeysAndValues2( MyCollection myCol )  {
      foreach ( String s in myCol.AllKeys )  {
         Console.WriteLine( "{0}, {1}", s, myCol[s] );
      }
   }
}


/*
This code produces the following output.

System.NotSupportedException: Collection is read-only.
   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
   at SamplesNameObjectCollectionBase.Main()
Read-Only Collection:
[0] : red, apple
[1] : yellow, banana
[2] : green, pear
Writable Collection (after adding values):
[0] : purple, grape
[1] : orange, tangerine
[2] : black, berries
Writable Collection (after changing one value):
[0] : purple, grape
[1] : orange, grapefruit
[2] : black, berries
Writable Collection (after removing one value):
[0] : purple, grape
[1] : orange, grapefruit
Writable Collection (after clearing the collection):

*/

[C++] 
#using <mscorlib.dll>
#using <system.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;

public __gc class MyCollection : public NameObjectCollectionBase
{
private:
   DictionaryEntry _de;

public:
   // Creates an empty collection.
   MyCollection() 
   {
   }

   // Adds elements from an IDictionary* into the new collection.
   MyCollection(IDictionary* d, Boolean bReadOnly)
   {
      IEnumerator* myEnum = d->GetEnumerator();
      while (myEnum->MoveNext()) {
         DictionaryEntry* de = __try_cast<DictionaryEntry*>(myEnum->Current);

         this->BaseAdd(dynamic_cast<String*>(de->Key), de->Value);
      }
      this->IsReadOnly = bReadOnly;
   }

   // Gets a key-and-value pair (DictionaryEntry) using an index.
   __property DictionaryEntry* get_Item( int index )
   {
      _de.Key = this->BaseGetKey(index);
      _de.Value = this->BaseGet(index);
      return(__box(_de));
   }

   // Gets or sets the value associated with the specified key.
   __property Object* get_Item( String* key ) 
   {
      return(this->BaseGet(key));
   }
   __property void set_Item( String* key, Object* value )
   {
      this->BaseSet(key, value);
   }

   // Gets a String array that contains all the keys in the collection.
   __property String* get_AllKeys()[]
   {
      return(this->BaseGetAllKeys());
   }

   // Gets an Object array that contains all the values in the collection.
   __property Object* get_AllValues()[]
   {
      return(this->BaseGetAllValues());
   }

   // Gets a String array that contains all the values in the collection.
   __property String* get_AllStringValues()[]
   {
      return(dynamic_cast<String*[]>(this->BaseGetAllValues(Type::GetType(S"System::String"))));
   }

   // Gets a value indicating if the collection contains keys that are not 0.
   Boolean HasKeys()
   {
      return(this->BaseHasKeys());
   }

   // Adds an entry to the collection.
   void Add(String* key, Object* value)
   {
      this->BaseAdd(key, value);
   }

   // Removes an entry with the specified key from the collection.
   void Remove(String* key)
   {
      this->BaseRemove(key);
   }

   // Removes an entry in the specified index from the collection.
   void Remove(int index)
   {
      this->BaseRemoveAt(index);
   }

   // Clears all the elements in the collection.
   void Clear()
   {
      this->BaseClear();
   }

};

// Prints the indexes, keys, and values.
void PrintKeysAndValues(MyCollection* myCol) {
   for (int i = 0; i < myCol->Count; i++) {
      Console::WriteLine(S"->Item[ {0}] : {1}, {2}", __box(i), myCol->Item[i]->Key, myCol->Item[i]->Value);
   }
}

// Prints the keys and values using AllKeys.
void PrintKeysAndValues2(MyCollection* myCol)
{
   IEnumerator* myEnum = myCol->AllKeys->GetEnumerator();
   while (myEnum->MoveNext())
   {
      String* s = __try_cast<String*>(myEnum->Current);

      Console::WriteLine(S" {0}, {1}", s, myCol->Item[s]);
   }
}

int main() 
{
   // Creates and initializes a new MyCollection that is read-only.
   IDictionary* d = new ListDictionary();
   d->Add(S"red", S"apple");
   d->Add(S"yellow", S"banana");
   d->Add(S"green", S"pear");
   MyCollection* myROCol = new MyCollection(d, true);

   // Tries to add a new item.
   try
   {
      myROCol->Add(S"blue", S"sky");
   }
   catch (NotSupportedException* e)
   {
      Console::WriteLine(e);
   }

   // Displays the keys and values of the MyCollection.
   Console::WriteLine(S"Read-Only Collection:");
   PrintKeysAndValues(myROCol);

   // Creates and initializes an empty MyCollection that is writable.
   MyCollection* myRWCol = new MyCollection();

   // Adds new items to the collection.
   myRWCol->Add(S"purple", S"grape");
   myRWCol->Add(S"orange", S"tangerine");
   myRWCol->Add(S"black", S"berries");
   Console::WriteLine(S"Writable Collection (after adding values):");
   PrintKeysAndValues(myRWCol);

   // Changes the value of one element.
   myRWCol->Item[S"orange"] = S"grapefruit";
   Console::WriteLine(S"Writable Collection (after changing one value):");
   PrintKeysAndValues(myRWCol);

   // Removes one item from the collection.
   myRWCol->Remove(S"black");
   Console::WriteLine(S"Writable Collection (after removing one value):");
   PrintKeysAndValues(myRWCol);

   // Removes all elements from the collection.
   myRWCol->Clear();
   Console::WriteLine(S"Writable Collection (after clearing the collection):");
   PrintKeysAndValues(myRWCol);
}

/*
This code produces the following output.

System::NotSupportedException: Collection is read-only.
   at System::Collections::Specialized::NameObjectCollectionBase.BaseAdd(String name, Object value)
   at SamplesNameObjectCollectionBase::Main()
Read-Only Collection:
[0] : red, apple
[1] : yellow, banana
[2] : green, pear
Writable Collection (after adding values):
[0] : purple, grape
[1] : orange, tangerine
[2] : black, berries
Writable Collection (after changing one value):
[0] : purple, grape
[1] : orange, grapefruit
[2] : black, berries
Writable Collection (after removing one value):
[0] : purple, grape
[1] : orange, grapefruit
Writable Collection (after clearing the collection):

*/

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.Collections.Specialized

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

アセンブリ: System (System.dll 内)

参照

NameObjectCollectionBase メンバ | System.Collections.Specialized 名前空間 | Hashtable | NameValueCollection | String | カルチャを認識しない文字列操作の実行