溫馨提示×

如何在C#中初始化Map集合

c#
小樊
175
2024-09-04 15:46:27
欄目: 編程語言

在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>實例。請根據您的需求選擇合適的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女