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

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

C# | Dictionary.Item[]属性

在 C# 中,Dictionary 类是用于表示键值对的集合的一种泛型类。Dictionary 类提供了 Item[] 属性来访问集合中的元素。在本文中,我们将深入探讨 C# 中的 Dictionary.Item[] 属性。

语法

Dictionary.Item[] 属性的完整语法如下:

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

其中,TKey 是 Dictionary 中键的类型,TValue 是 Dictionary 中值的类型,key 是要访问的元素的键。该属性是一个索引器,可以用于访问 Dictionary 中指定键的值。

示例

以下是使用 Dictionary.Item[] 属性的示例程序:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> scores = new Dictionary<string, int>();
        scores.Add("Alice", 90);
        scores.Add("Bob", 80);
        scores.Add("Charlie", 70);

        int aliceScore = scores["Alice"];
        Console.WriteLine("Alice's score is {0}", aliceScore);

        scores["Bob"] = 85;
        Console.WriteLine("Bob's new score is {0}", scores["Bob"]);
    }
}

在上面的程序中,我们创建了一个包含三个元素的 Dictionary,并使用 Item[] 属性来获取和设置其中的元素。在第一次使用 Item[] 属性时,我们获取了 Alice 的分数,并将其输出到控制台。接着,我们使用 Item[] 属性修改了 Bob 的分数,并再次使用 Item[] 属性获取了 Bob 的分数并输出到控制台。

运行此程序将输出以下内容:

Alice's score is 90
Bob's new score is 85
注意事项
  • 如果 Dictionary 中不存在指定键的元素,则使用 Item[] 属性将引发 KeyNotFoundException 异常。
  • 如果使用 Item[] 属性设置一个键的值,但该键不存在于 Dictionary 中,则将添加一个新元素。
  • 当使用 Item[] 属性访问 Dictionary 中的元素时,请注意空引用。
总结

Dictionary 类是 C# 中用于表示键值对集合的类。它提供了 Item[] 属性,可以使用该属性访问集合中的元素。我们可以使用 Item[] 属性获取或设置 Dictionary 中指定键的值。如果 Dictionary 中不存在指定键的元素,则使用 Item[] 属性将引发异常。在使用 Item[] 属性访问 Dictionary 中的元素时,请注意空引用。