在C#中,您可以使用Dictionary<TKey, TValue>来表示Map集合
方法1:使用Collection Initializer语法(需要C# 3.0及更高版本)
using System;using System.Collections.Generic;class Program{ static void Main() { var map = new Dictionary<string, int> { {"one", 1}, {"two", 2}, {"three", 3} }; foreach (var item in map) { Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"); } }}方法2:使用Add()方法逐个添加元素
using System;using System.Collections.Generic;class Program{ static void Main() { var map = new Dictionary<string, int>(); map.Add("one", 1); map.Add("two", 2); map.Add("three", 3); foreach (var item in map) { Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"); } }}这两种方法都会创建一个包含三个键值对的Dictionary<string, int>实例。请根据您的需求选择合适的方法。


