System.Collections.Hashtable.Clear 方法

方法描述

从 Hashtable 中移除所有元素。

语法定义(C# System.Collections.Hashtable.Clear 方法 的用法)

public virtual void Clear()

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
返回值 void

提示和注释

Count 被设置为零,并且对来自该集合元素的其他对象的引用也被释放。 容量保持不变。

此方法的运算复杂度为 O(n),其中 n 是 Count。

System.Collections.Hashtable.Clear 方法例子

下面的示例说明如何清除 Hashtable 的值。

using System;
 using System.Collections;
 public class SamplesHashtable  {

    public static void Main()  {

       // Creates and initializes a new Hashtable.
       Hashtable myHT = new Hashtable();
       myHT.Add( "one", "The" );
       myHT.Add( "two", "quick" );
       myHT.Add( "three", "brown" );
       myHT.Add( "four", "fox" );
       myHT.Add( "five", "jumped" );

       // Displays the count and values of the Hashtable.
       Console.WriteLine( "Initially," );
       Console.WriteLine( "   Count    : {0}", myHT.Count );
       Console.WriteLine( "   Values:" );
       PrintKeysAndValues( myHT );

       // Clears the Hashtable.
       myHT.Clear();

       // Displays the count and values of the Hashtable.
       Console.WriteLine( "After Clear," );
       Console.WriteLine( "   Count    : {0}", myHT.Count );
       Console.WriteLine( "   Values:" );
       PrintKeysAndValues( myHT );
    }


    public static void PrintKeysAndValues( Hashtable myHT )  {
       Console.WriteLine( "\t-KEY-\t-VALUE-" );
       foreach ( DictionaryEntry de in myHT )
          Console.WriteLine( "\t{0}:\t{1}", de.Key, de.Value );
       Console.WriteLine();
    }

 }


 /* 
 This code produces the following output.

 Initially,
    Count    : 5
    Values:
         -KEY-   -VALUE-
         two:    quick
         three:  brown
         four:   fox
         five:   jumped
         one:    The

 After Clear,
    Count    : 0
    Values:
         -KEY-   -VALUE-

 */

异常

异常 异常描述
NotSupportedException Hashtable 是只读的。

命名空间

namespace: System.Collections

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。