DictionaryBase 类

定义

为键/值对的强类型集合提供 abstract 基类。

C#
public abstract class DictionaryBase : System.Collections.IDictionary
C#
[System.Serializable]
public abstract class DictionaryBase : System.Collections.IDictionary
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class DictionaryBase : System.Collections.IDictionary
继承
DictionaryBase
派生
属性
实现

示例

下面的代码示例实现 DictionaryBase 类,并使用该实现创建包含 5 个字符或更少字符的键和值的Length字典String

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() != typeof(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() != typeof(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() != typeof(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() != typeof(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() != typeof(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() != typeof(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() != typeof(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" );

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

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

      // Display the contents of the collection using the Keys property and the Item property.
      Console.WriteLine( "Initial contents of the collection (using Keys and Item):" );
      PrintKeysAndValues3( mySSC );

      // 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();

      // 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.
      Console.WriteLine( "After removing \"Two\":" );
      PrintKeysAndValues1( mySSC );
   }

   // 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 PrintKeysAndValues1( ShortStringDictionary myCol )  {
      foreach ( DictionaryEntry myDE in myCol )
         Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
      Console.WriteLine();
   }

   // Uses the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintKeysAndValues2( 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 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.

Contents of the collection (using foreach):
   Three : abc
   Five  : abcde
   Two   : ab
   One   : a
   Four  : abcd

Contents of the collection (using enumerator):
   Three : abc
   Five  : abcde
   Two   : ab
   One   : a
   Four  : abcd

Initial contents of the collection (using Keys and Item):
   Three : abc
   Five  : abcde
   Two   : ab
   One   : a
   Four  : abcd

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()

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

After removing "Two":
   Three : abc
   Five  : abcde
   One   : a
   Four  : abcd

*/

注解

重要

不建议使用 DictionaryBase 类进行新开发。 建议改用泛型 Dictionary<TKey,TValue>KeyedCollection<TKey,TItem> 类 。 有关详细信息,请参阅 不应在 GitHub 上使用非泛型集合

C# foreach 语句和 Visual Basic For Each 语句返回集合中元素类型的对象。 由于 的每个 DictionaryBase 元素都是键/值对,因此元素类型不是键的类型或值的类型。 相反,元素类型为 DictionaryEntry

语句 foreach 是枚举器周围的包装器,它只允许从集合中读取,而不允许写入集合。

备注

由于密钥可以继承并更改其行为,因此无法使用 方法进行比较 Equals 来保证其绝对唯一性。

实施者说明

提供此基类是为了便于实现者创建强类型自定义集合。 建议实现者扩展此基类,而不是创建自己的基类。

此基类的成员受到保护,仅通过派生类使用。

构造函数

DictionaryBase()

初始化 DictionaryBase 类的新实例。

属性

Count

获取 DictionaryBase 实例中包含的元素数。

Dictionary

获取 DictionaryBase 实例中包含的元素的列表。

InnerHashtable

获取 DictionaryBase 实例中包含的元素的列表。

方法

Clear()

清除 DictionaryBase 实例的内容。

CopyTo(Array, Int32)

DictionaryBase 元素复制到位于指定索引处的一维 Array 中。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetEnumerator()

返回循环访问 IDictionaryEnumerator 实例的 DictionaryBase

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
OnClear()

在清除 DictionaryBase 实例的内容之前执行其他自定义进程。

OnClearComplete()

在清除 DictionaryBase 实例的内容之后执行其他自定义进程。

OnGet(Object, Object)

获取 DictionaryBase 实例中带有指定键和值的元素。

OnInsert(Object, Object)

在向 DictionaryBase 实例中插入新元素之前执行其他自定义进程。

OnInsertComplete(Object, Object)

在向 DictionaryBase 实例中插入新元素之后执行其他自定义进程。

OnRemove(Object, Object)

当从 DictionaryBase 实例移除元素时执行其他自定义进程。

OnRemoveComplete(Object, Object)

在从 DictionaryBase 实例中移除元素之后执行其他自定义进程。

OnSet(Object, Object, Object)

当在 DictionaryBase 实例中设置值之前执行其他自定义进程。

OnSetComplete(Object, Object, Object)

当在 DictionaryBase 实例中设置值后执行其他自定义进程。

OnValidate(Object, Object)

在验证具有指定键和值的元素时执行其他自定义进程。

ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

ICollection.IsSynchronized

获取一个值,该值指示对 DictionaryBase 对象的访问是否同步(线程安全)。

ICollection.SyncRoot

获取一个对象,该对象可用于同步对 DictionaryBase 对象的访问。

IDictionary.Add(Object, Object)

将带有指定键和值的元素添加到 DictionaryBase 中。

IDictionary.Contains(Object)

确定 DictionaryBase 是否包含特定键。

IDictionary.IsFixedSize

获取一个值,该值指示 DictionaryBase 对象是否具有固定大小。

IDictionary.IsReadOnly

获取一个值,该值指示 DictionaryBase 对象是否为只读。

IDictionary.Item[Object]

获取或设置与指定的键关联的值。

IDictionary.Keys

获取包含 ICollection 对象中的键的 DictionaryBase 对象。

IDictionary.Remove(Object)

DictionaryBase 中移除包含指定键的元素。

IDictionary.Values

获取 ICollection 对象,它包含 DictionaryBase 对象中的值。

IEnumerable.GetEnumerator()

返回循环访问 IEnumeratorDictionaryBase

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。

AsParallel(IEnumerable)

启用查询的并行化。

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryable

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

线程安全性

Visual Basic 中的公共静态 (Shared) 此类型的成员是线程安全的。 但不保证所有实例成员都是线程安全的。

此实现不会为 DictionaryBase提供同步 (线程安全的) 包装器,但派生类可以使用 属性创建自己的同步版本的 DictionaryBaseSyncRoot

枚举整个集合本质上不是一个线程安全的过程。 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。

另请参阅