📜  C#| SortedDictionary.Item []属性(1)

📅  最后修改于: 2023-12-03 15:00:14.797000             🧑  作者: Mango

C# | SortedDictionary.Item[]属性

在 C# 中,SortedDictionary 是一种泛型集合,它基于键/值对存储元素,并可根据键的比较器进行排序。SortedDictionary 类提供了一些有用的属性和方法来处理键值对集合,其中 Item[] 属性是其中之一。

Item[] 属性

Item[] 属性是 SortedDictionary 类的默认属性,可用于访问指定键所对应的值。具体而言,可以通过索引器语法(即将 SortedDictionary 实例作为数组一样访问)来获取或设置键值对。

以下是 Item[] 属性的语法:

public TValue this[TKey key] { get; set; }

其中,TKey 表示键的类型,TValue 表示值的类型。通过该语法,可以根据键值对的键获取或设置键值对的值。

下面的示例代码演示了如何使用 SortedDictionary.Item[] 属性:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 创建 SortedDictionary 实例
        SortedDictionary<string, int> scores = new SortedDictionary<string, int>();

        // 添加键值对
        scores.Add("Peter", 90);
        scores.Add("John", 85);
        scores.Add("Mike", 70);

        // 使用 Item[] 获取或设置值
        int peterScore = scores["Peter"];
        scores["John"] = 90;
        scores["Mike"] += 10;

        // 遍历输出所有元素
        foreach (KeyValuePair<string, int> kvp in scores)
        {
            Console.WriteLine("{0} scored {1}", kvp.Key, kvp.Value);
        }
    }
}

输出:

John scored 90
Mike scored 80
Peter scored 90
注意事项

需要注意以下几点:

  • 使用 Item[] 时,若指定的键不存在,将会引发 System.Collections.Generic.KeyNotFoundException 异常。
  • 确保键的类型正确匹配,否则将引发 System.ArgumentException 异常。
  • 如果在 SortedDictionary 实例中添加相同的键,则新值将替换旧值。
  • SortedDictionary 是一个有序集合,因此它的元素按照键进行排序。在上述示例代码中,键是字符串类型,按照字母顺序排序。如果键是数字类型,则按照数字顺序排序。
结论

SortedDictionary.Item[] 属性是 SortedDictionary 类的重要属性之一。通过该属性,可以方便地获取或设置键值对中的值。当需要从 SortedDictionary 实例中按照键查找值时,Item[] 将成为一个非常有用的工具。