使用英语阅读

通过


DictionaryBase.System.Collections.IDictionary.Item Property

Note: This namespace, class, or member is supported only in version 1.1 of the .NET Framework.

Gets or sets the value associated with the specified key.

[C#] In C#, this property is the indexer for the DictionaryBase class.

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);-or-private function get IDictionary.get_Item(key : Object) : Object;private function set IDictionary.set_Item(key : Object, value : Object);

[JScript] In JScript, you can use the default indexed properties defined by a type, but you cannot explicitly define your own. However, specifying the expando attribute on a class automatically provides a default indexed property whose type is Object and whose index type is String.

Arguments [JScript]

  • key
    The key whose value to get or set.

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

  • key
    The key whose value to get or set.

Property Value

The value associated with the specified key. If the specified key is not found, attempting to get it returns a null reference (Nothing in Visual Basic), and attempting to set it creates a new element using the specified key.

Implements

IDictionary.Item

Exceptions

Exception Type Condition
ArgumentNullException key is a null reference (Nothing in Visual Basic).
NotSupportedException The property is set and the DictionaryBase is read-only.

-or-

The property is set, key does not exist in the collection, and the DictionaryBase has a fixed size.

Remarks

This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[key].

When setting this property, if the specified key already exists in the DictionaryBase, the value is replaced; otherwise, a new element is created. In contrast, the Add method does not modify existing elements.

Example

[Visual Basic, C#, C++] The following code example implements the DictionaryBase class and uses that implementation to create a dictionary of String keys and values that have a Length of 5 characters or less.

 
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] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

DictionaryBase Class | DictionaryBase Members | System.Collections Namespace | Add