Freigeben über


DictionaryBase.System.Collections.IDictionary.Item-Eigenschaft

Hinweis: Dieser Namespace oder Member bzw. diese Klasse wird nur von .NET Framework, Version 1.1, unterstützt.

Ruft den Wert ab, der dem angegebenen Schlüssel zugeordnet ist, oder legt diesen fest.

[C#] In C# stellt diese Eigenschaft den Indexer für die DictionaryBase-Klasse dar.

Private Default Property Item( _
   ByVal key As Object _) As Object Implements IDictionary.Item
[C#]
object IDictionary.this[
   objectkey] {get; set;}
[C++]
private: __property Object* System::Collections::IDictionary::get_Item(Object* key);private: __property void   System::Collections::IDictionary::set_Item(Object* key,   Object*);
[JScript]
private function get IDictionary.get_Item(key : Object) : Object;private function set IDictionary.set_Item(key : Object, value : Object);- oder -private function get IDictionary.get_Item(key : Object) : Object;private function set IDictionary.set_Item(key : Object, value : Object);

[JScript] In JScript können Sie die durch einen Typ definierten indizierten Standardeigenschaften verwenden, jedoch keine eigenen explizit definieren. Durch Angabe des expando-Attributs für eine Klasse wird allerdings automatisch eine indizierte Standardeigenschaft mit dem Typ Object und dem Indextyp String bereitgestellt.

Argumente [JScript]

  • key
    Der Schlüssel, dessen Wert abgerufen oder festgelegt werden soll.

Parameter [Visual Basic, C#, C++]

  • key
    Der Schlüssel, dessen Wert abgerufen oder festgelegt werden soll.

Eigenschaftenwert

Der dem angegebenen Schlüssel zugeordnete Wert. Wenn der angegebene Schlüssel nicht gefunden werden kann, wird beim Abrufen dieses Schlüssels NULL (Nothing in Visual Basic) zurückgegeben. Beim Festlegen wird ein neues Element mit dem angegebenen Schlüssel erstellt.

Implementiert

IDictionary.Item

Ausnahmen

Ausnahmetyp Bedingung
ArgumentNullException key ist NULL (Nothing in Visual Basic).
NotSupportedException Die Eigenschaft wird festgelegt, und DictionaryBase ist schreibgeschützt.

– oder –

Die Eigenschaft wird festgelegt, key ist in der Auflistung nicht vorhanden, und DictionaryBase hat eine feste Größe.

Hinweise

Diese Eigenschaft ermöglicht den Zugriff auf ein bestimmtes Element in der Auflistung mit folgender Syntax: myCollection[key].

Wenn der angegebene Schlüssel beim Festlegen dieser Eigenschaft bereits in DictionaryBase vorhanden ist, wird der Wert ersetzt. Andernfalls wird ein neues Element erstellt. Im Gegensatz dazu ändert die Add-Methode keine vorhandenen Elemente.

Beispiel

[Visual Basic, C#, C++] Im folgenden Codebeispiel wird die DictionaryBase-Klasse implementiert und diese Implementierung zum Erstellen eines Wörterbuchs aus String-Schlüsseln und -Werten mit einer Length von höchstens 5 Zeichen verwendet.

 
Imports System
Imports System.Collections

Public Class ShortStringDictionary
   Inherits DictionaryBase

   Default Public Property Item(key As [String]) As [String]
      Get
         Return CType(Dictionary(key), [String])
      End Get
      Set
         Dictionary(key) = value
      End Set
   End Property

   Public ReadOnly Property Keys() As ICollection
      Get
         Return Dictionary.Keys
      End Get
   End Property

   Public ReadOnly Property Values() As ICollection
      Get
         Return Dictionary.Values
      End Get
   End Property

   Public Sub Add(key As [String], value As [String])
      Dictionary.Add(key, value)
   End Sub 'Add

   Public Function Contains(key As [String]) As Boolean
      Return Dictionary.Contains(key)
   End Function 'Contains

   Public Sub Remove(key As [String])
      Dictionary.Remove(key)
   End Sub 'Remove

   Protected Overrides Sub OnInsert(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not value.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("value must be of type String.", "value")
      Else
         Dim strValue As [String] = CType(value, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
         End If
      End If
   End Sub 'OnInsert

   Protected Overrides Sub OnRemove(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If
   End Sub 'OnRemove

   Protected Overrides Sub OnSet(key As [Object], oldValue As [Object], newValue As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not newValue.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("newValue must be of type String.", "newValue")
      Else
         Dim strValue As [String] = CType(newValue, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("newValue must be no more than 5 characters in length.", "newValue")
         End If
      End If
   End Sub 'OnSet

   Protected Overrides Sub OnValidate(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not value.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("value must be of type String.", "value")
      Else
         Dim strValue As [String] = CType(value, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
         End If
      End If
   End Sub 'OnValidate 

End Class 'ShortStringDictionary


Public Class SamplesDictionaryBase

   Public Shared Sub Main()

      ' Creates and initializes a new DictionaryBase.
      Dim mySSC As New ShortStringDictionary()

      ' Adds elements to the collection.
      mySSC.Add("One", "a")
      mySSC.Add("Two", "ab")
      mySSC.Add("Three", "abc")
      mySSC.Add("Four", "abcd")
      mySSC.Add("Five", "abcde")

      ' Tries to add a value that is too long.
      Try
         mySSC.Add("Ten", "abcdefghij")
      Catch e As ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      ' Tries to add a key that is too long.
      Try
         mySSC.Add("Eleven", "ijk")
      Catch e As ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      Console.WriteLine()

      ' Displays the contents of the collection using the enumerator.
      Console.WriteLine("Initial contents of the collection:")
      PrintKeysAndValues(mySSC)

      ' Searches the collection with Contains.
      Console.WriteLine("Contains ""Three"": {0}", mySSC.Contains("Three"))
      Console.WriteLine("Contains ""Twelve"": {0}", mySSC.Contains("Twelve"))
      Console.WriteLine()

      ' Removes an element from the collection.
      mySSC.Remove("Two")

      ' Displays the contents of the collection using the Keys property.
      Console.WriteLine("New state of the collection:")
      PrintKeysAndValues3(mySSC)

   End Sub 'Main

   ' Uses the enumerator. 
   Public Shared Sub PrintKeysAndValues(myCol As ShortStringDictionary)
      Dim myDE As DictionaryEntry
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
         If Not (myEnumerator.Current Is Nothing) Then
            myDE = CType(myEnumerator.Current, DictionaryEntry)
            Console.WriteLine("   {0,-5} : {1}", myDE.Key, myDE.Value)
         End If
      End While
      Console.WriteLine()
   End Sub 'PrintKeysAndValues

   ' Uses the foreach statement which hides the complexity of the enumerator.
   Public Shared Sub PrintKeysAndValues2(myCol As ShortStringDictionary)
      Dim myDE As DictionaryEntry
      For Each myDE In  myCol
         Console.WriteLine("   {0,-5} : {1}", myDE.Key, myDE.Value)
      Next myDE
      Console.WriteLine()
   End Sub 'PrintKeysAndValues2

   ' Uses the Keys property and the Item property.
   Public Shared Sub PrintKeysAndValues3(myCol As ShortStringDictionary)
      Dim myKeys As ICollection = myCol.Keys
      Dim k As [String]
      For Each k In  myKeys
         Console.WriteLine("   {0,-5} : {1}", k, myCol(k))
      Next k
      Console.WriteLine()
   End Sub 'PrintKeysAndValues3

End Class 'SamplesDictionaryBase 

 
'This code produces the following output.
'
'System.ArgumentException: value must be no more than 5 characters in length.
'Parameter name: value
'   at ShortStringDictionary.OnValidate(Object key, Object value)
'   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
'   at SamplesDictionaryBase.Main()
'System.ArgumentException: key must be no more than 5 characters in length.
'Parameter name: key
'   at ShortStringDictionary.OnValidate(Object key, Object value)
'   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
'   at SamplesDictionaryBase.Main()
'
'Initial contents of the collection:
'   One   : a
'   Four  : abcd
'   Three : abc
'   Two   : ab
'   Five  : abcde
'
'Contains "Three": True
'Contains "Twelve": False
'
'New state of the collection:
'   One   : a
'   Four  : abcd
'   Three : abc
'   Five  : abcde


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

public class ShortStringDictionary : DictionaryBase  {

   public String this[ String key ]  {
      get  {
         return( (String) Dictionary[key] );
      }
      set  {
         Dictionary[key] = value;
      }
   }

   public ICollection Keys  {
      get  {
         return( Dictionary.Keys );
      }
   }

   public ICollection Values  {
      get  {
         return( Dictionary.Values );
      }
   }

   public void Add( String key, String value )  {
      Dictionary.Add( key, value );
   }

   public bool Contains( String key )  {
      return( Dictionary.Contains( key ) );
   }

   public void Remove( String key )  {
      Dictionary.Remove( key );
   }

   protected override void OnInsert( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "value must be of type String.", "value" );
      else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

   protected override void OnRemove( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }
   }

   protected override void OnSet( Object key, Object oldValue, Object newValue )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( newValue.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "newValue must be of type String.", "newValue" );
      else  {
         String strValue = (String) newValue;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" );
      }
   }

   protected override void OnValidate( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "value must be of type String.", "value" );
      else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

}


public class SamplesDictionaryBase  {

   public static void Main()  {
 
      // Creates and initializes a new DictionaryBase.
      ShortStringDictionary mySSC = new ShortStringDictionary();

      // Adds elements to the collection.
      mySSC.Add( "One", "a" );
      mySSC.Add( "Two", "ab" );
      mySSC.Add( "Three", "abc" );
      mySSC.Add( "Four", "abcd" );
      mySSC.Add( "Five", "abcde" );

      // Tries to add a value that is too long.
      try  {
         mySSC.Add( "Ten", "abcdefghij" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Tries to add a key that is too long.
      try  {
         mySSC.Add( "Eleven", "ijk" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      Console.WriteLine();

      // Displays the contents of the collection using the enumerator.
      Console.WriteLine( "Initial contents of the collection:" );
      PrintKeysAndValues( mySSC );

      // Searches the collection with Contains.
      Console.WriteLine( "Contains \"Three\": {0}", mySSC.Contains( "Three" ) );
      Console.WriteLine( "Contains \"Twelve\": {0}", mySSC.Contains( "Twelve" ) );
      Console.WriteLine();

      // Removes an element from the collection.
      mySSC.Remove( "Two" );

      // Displays the contents of the collection using the Keys property.
      Console.WriteLine( "New state of the collection:" );
      PrintKeysAndValues3( mySSC );

   }

   // Uses the enumerator. 
   public static void PrintKeysAndValues( ShortStringDictionary myCol )  {
      DictionaryEntry myDE;
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         if ( myEnumerator.Current != null )  {
            myDE = (DictionaryEntry) myEnumerator.Current;
            Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
         }
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   public static void PrintKeysAndValues2( ShortStringDictionary myCol )  {
      foreach ( DictionaryEntry myDE in myCol )
         Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
      Console.WriteLine();
   }

   // Uses the Keys property and the Item property.
   public static void PrintKeysAndValues3( ShortStringDictionary myCol )  {
      ICollection myKeys = myCol.Keys;
      foreach ( String k in myKeys )
         Console.WriteLine( "   {0,-5} : {1}", k, myCol[k] );
      Console.WriteLine();
   }

}


/* 
This code produces the following output.

System.ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()
System.ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()

Initial contents of the collection:
   One   : a
   Four  : abcd
   Three : abc
   Two   : ab
   Five  : abcde

Contains "Three": True
Contains "Twelve": False

New state of the collection:
   One   : a
   Four  : abcd
   Three : abc
   Five  : abcde

*/


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

using namespace System;
using namespace System::Collections;

public __gc class ShortStringDictionary : public DictionaryBase
{
public:
   __property String* get_Item( String* key )
   {
      return __try_cast<String*>(Dictionary->Item[key]);
   }

   __property void set_Item( String* key, String* value )
   {
      Dictionary->Item[key] = value;
   }

   __property ICollection* get_Keys()
   {
      return(Dictionary->Keys);
   }

   __property ICollection* get_Values()
   {
      return(Dictionary->Values);
   }

   void Add(String* key, String* value) {
      Dictionary->Add(key, value);
   }

   bool Contains(String* key) {
      return(Dictionary->Contains(key));
   }

   void Remove(String* key) {
      Dictionary->Remove(key);
   }

protected:
   void OnInsert(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (value->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"value must be of type String.", S"value");
      else {
         String* strValue = __try_cast<String*>(value);
         if (strValue->Length > 5)
            throw new ArgumentException(S"value must be no more than 5 characters in length.", S"value");
      }
   }

   void OnRemove(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }
   }

   void OnSet(Object* key, Object* oldValue, Object* newValue) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (newValue->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"newValue must be of type String.", S"newValue");
      else {
         String* strValue = __try_cast<String*>(newValue);
         if (strValue->Length > 5)
            throw new ArgumentException(S"newValue must be no more than 5 characters in length.", S"newValue");
      }
   }

   void OnValidate(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else 
      {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (value->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"value must be of type String.", S"value");
      else 
      {
         String* strValue = __try_cast<String*>(value);
         if (strValue->Length > 5)
            throw new ArgumentException(S"value must be no more than 5 characters in length.", S"value");
      }
   }
};

// Uses the enumerator. 
void PrintKeysAndValues(ShortStringDictionary* myCol)
{
   DictionaryEntry* myDE;
   System::Collections::IEnumerator* myEnumerator = myCol->GetEnumerator();
   while (myEnumerator->MoveNext())
      if (myEnumerator->Current != 0)
      {
         myDE = __try_cast<DictionaryEntry*>(myEnumerator->Current);
         Console::WriteLine(S" {0, -5} : {1}", myDE->Key, myDE->Value);
      }
      Console::WriteLine();
}

// Uses the foreach statement which hides the complexity of the enumerator.
void PrintKeysAndValues2(ShortStringDictionary* myCol) 
{
   IEnumerator* myEnum = myCol->GetEnumerator();
   while (myEnum->MoveNext())
   {
      DictionaryEntry* myDE = __try_cast<DictionaryEntry*>(myEnum->Current);

      Console::WriteLine(S" {0, -5} : {1}", myDE->Key, myDE->Value);
      Console::WriteLine();
   }
}
// Uses the Keys property and the Item property.
void PrintKeysAndValues3(ShortStringDictionary* myCol) 
{
   ICollection* myKeys = myCol->Keys;
   IEnumerator* myEnum = myKeys->GetEnumerator();
   while (myEnum->MoveNext())
   {
      String* k = __try_cast<String*>(myEnum->Current);

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

int main() 
{
   // Creates and initializes a new DictionaryBase.
   ShortStringDictionary* mySSC = new ShortStringDictionary();

   // Adds elements to the collection.
   mySSC->Add(S"One", S"a");
   mySSC->Add(S"Two", S"ab");
   mySSC->Add(S"Three", S"abc");
   mySSC->Add(S"Four", S"abcd");
   mySSC->Add(S"Five", S"abcde");

   // Tries to add a value that is too long.
   try
   {
      mySSC->Add(S"Ten", S"abcdefghij");
   }
   catch (ArgumentException* e)
   {
      Console::WriteLine(e);
   }

   // Tries to add a key that is too long.
   try
   {
      mySSC->Add(S"Eleven", S"ijk");
   }
   catch (ArgumentException* e)
   {
      Console::WriteLine(e);
   }

   Console::WriteLine();

   // Displays the contents of the collection using the enumerator.
   Console::WriteLine(S"Initial contents of the collection:");
   PrintKeysAndValues(mySSC);

   // Searches the collection with Contains.
   Console::WriteLine(S"Contains \"Three\": {0}", __box(mySSC->Contains(S"Three")));
   Console::WriteLine(S"Contains \"Twelve\": {0}", __box(mySSC->Contains(S"Twelve")));
   Console::WriteLine();

   // Removes an element from the collection.
   mySSC->Remove(S"Two");

   // Displays the contents of the collection using the Keys property.
   Console::WriteLine(S"New state of the collection:");
   PrintKeysAndValues3(mySSC);
}

/* 
This code produces the following output.

System::ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
at ShortStringDictionary::OnValidate(Object key, Object value)
at System::Collections::DictionaryBase::System.Collections::IDictionary*.Add(Object key, Object value)
at SamplesDictionaryBase::Main()
System::ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
at ShortStringDictionary::OnValidate(Object key, Object value)
at System::Collections::DictionaryBase::System.Collections::IDictionary*.Add(Object key, Object value)
at SamplesDictionaryBase::Main()

Initial contents of the collection:
One   : a
Four  : abcd
Three : abc
Two   : ab
Five  : abcde

Contains S"Three": True
Contains S"Twelve": False

New state of the collection:
One   : a
Four  : abcd
Three : abc
Five  : abcde

*/

[JScript] Für JScript ist kein Beispiel verfügbar. Klicken Sie zum Anzeigen eines Beispiels für Visual Basic, C# oder C++ in der linken oberen Ecke der Seite auf die Schaltfläche "Sprachfilter" Sprachfilter.

Anforderungen

Plattformen: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003-Familie

Siehe auch

DictionaryBase-Klasse | DictionaryBase-Member | System.Collections-Namespace | Add