如何在 C# 中更新字典中的值?

csharpserver side programmingprogramming更新于 2025/6/29 5:52:17

在 C# 中,字典是一个泛型集合,通常用于存储键/值对。字典中的键不能为空,但值可以为空。键必须唯一。不允许使用重复的键,如果尝试使用重复的键,编译器将抛出异常。

如上所述,字典中的值可以通过使用其键来更新,因为键对于每个值都是唯一的。

myDictionary[myKey] = myNewValue;

示例

假设一个包含学生 ID 和姓名的字典。现在,我们想将 ID 为 2 的学生的姓名从"Mrk"更改为"Mark"。

using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Program{
      static void Main(string[] args){
         Dictionary<int, string> students = new Dictionary<int, string>{
            { 1, "John" },
            { 2, "Mrk" },
            { 3, "Bill" }
         };
         Console.WriteLine($"Name of student having id 2: {students[2]}");
         students[2] = "Mark";
         Console.WriteLine($"Updated Name of student having id 2: {students[2]}");
         Console.ReadLine();
      }
   }
}

输出

上述代码的输出是 −

Name of student having id 2: Mrk
Updated Name of student having id 2: Mark

相关文章