📜  C#|获取或设置与哈希表中指定键关联的值

📅  最后修改于: 2021-05-29 20:42:09             🧑  作者: Mango

Hashtable.Item [Object]属性用于获取或设置与Hashtable中的指定键关联的值。

句法:

public virtual object this[object key] { get; set; }

在此,是要获取或设置其值的对象类型的键。

例外情况:

  • ArgumentNullException:如果为null。
  • NotSupportedException:如果设置了属性并且Hashtable是只读的。或设置了属性,在集合中不存在,并且哈希表具有固定的大小。

笔记:

  • 此属性返回与特定键关联的值。如果未找到该键,而一个人试图获取该键,则此属性将返回null;如果尝试设置该属性,则将导致使用指定的键创建一个新元素。
  • 检索和设置此属性的值是O(1)操作。

下面的程序说明了上面讨论的属性的用法:

范例1:

// C# code to Gets or sets the value
// associated with the specified key
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable
        Hashtable myTable = new Hashtable();
  
        // Adding elements in Hashtable
        myTable.Add("g", "geeks");
        myTable.Add("c", "c++");
        myTable.Add("d", "data structures");
        myTable.Add("q", "quiz");
  
        // Get a collection of the keys.
        ICollection c = myTable.Keys;
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + myTable[str]);
  
        // Setting the value associated with key "c"
        myTable["c"] = "C#";
  
        Console.WriteLine("Updated Values:");
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + myTable[str]);
    }
}
输出:
d: data structures
c: c++
q: quiz
g: geeks
Updated Values:
d: data structures
c: C#
q: quiz
g: geeks

范例2:

// C# code to Gets or sets the value
// associated with the specified key
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable
        Hashtable myTable = new Hashtable();
  
        // Adding elements in Hashtable
        myTable.Add("4", "Even");
        myTable.Add("9", "Odd");
        myTable.Add("5", "Odd and Prime");
        myTable.Add("2", "Even and Prime");
  
        // Get a collection of the keys.
        ICollection c = myTable.Keys;
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + myTable[str]);
  
        // Setting the value associated
        // with key "56" which is not present 
        // will result in the creation of 
        // new key and value will be set which 
        // is given by the user
        myTable["56"] = "New Value";
  
        Console.WriteLine("Updated Values:");
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + myTable[str]);
    }
}
输出:
5: Odd and Prime
9: Odd
2: Even and Prime
4: Even
Updated Values:
5: Odd and Prime
9: Odd
2: Even and Prime
56: New Value
4: Even

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.item?view=netframework-4.7.2