📌  相关文章
📜  C#|使用指定的键获取或设置HybridDictionary中的值

📅  最后修改于: 2021-05-30 00:49:39             🧑  作者: Mango

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

句法:

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

在此, key是要获取或设置其值的键。

返回值:与指定键关联的值。如果找不到指定的键,则尝试获取它会返回null ,然后尝试设置它会使用指定的键创建一个新条目。

异常:如果键为null,则此属性将提供ArgumentNullException

下面的程序说明了HybridDictionary.Item [Object]属性的用法:

范例1:

// C# code to get or set the value
// associated with the specified key
// in HybridDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary named myDict
        HybridDictionary myDict = new HybridDictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("Australia", "Canberra");
        myDict.Add("Belgium", "Brussels");
        myDict.Add("Netherlands", "Amsterdam");
        myDict.Add("China", "Beijing");
        myDict.Add("Russia", "Moscow");
        myDict.Add("India", "New Delhi");
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
  
        // Displaying the value associated
        // with key "Russia"
        Console.WriteLine(myDict["Russia"]);
  
        // Setting the value associated with key "Russia"
        myDict["Russia"] = "Saint Petersburg";
  
        // Displaying the value associated
        // with key "Russia"
        Console.WriteLine(myDict["Russia"]);
  
        // Displaying the value associated
        // with key "India"
        Console.WriteLine(myDict["India"]);
  
        // Setting the value associated with key "India"
        myDict["India"] = "Mumbai";
  
        // Displaying the value associated
        // with key "India"
        Console.WriteLine(myDict["India"]);
  
        // Displaying the key/value pairs in myDict
        foreach(DictionaryEntry de in myDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
    }
}

输出:

Australia Canberra
Belgium Brussels
Netherlands Amsterdam
China Beijing
Russia Moscow
India New Delhi
Moscow
Saint Petersburg
New Delhi
Mumbai
Australia Canberra
Belgium Brussels
Netherlands Amsterdam
China Beijing
Russia Saint Petersburg
India Mumbai

笔记:

  • 通过使用以下语法,可以使用此属性访问集合中的特定元素: myCollection [key]
  • 键不能为null ,但值可以。
  • 检索此属性的值是O(1)操作。设置属性也是O(1)操作。

参考:

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