You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中new Map()对应的C#等效实现是什么?

C# 等效实现说明

C# 中与 JavaScript Map 功能最精确对应的是 System.Collections.Generic 命名空间下的泛型字典类 Dictionary<TKey, TValue>,具体用法对比如下:

  • 初始化
    JS 写法:

    const something = new Map();
    

    C# 等效写法(以键为string类型、值为int类型为例,可根据实际需求替换类型参数,若需要和JS一样支持任意类型的键值,可使用Dictionary<object, object>):

    using System.Collections.Generic;
    // 初始化字典
    Dictionary<string, int> something = new Dictionary<string, int>();
    
  • 存值操作(对应Map.set())
    JS 写法:

    something.set('testKey', 123);
    

    C# 等效写法(和set行为完全一致,键存在时会覆盖旧值):

    something["testKey"] = 123;
    

    如果你需要在键重复时抛出异常避免意外覆盖,可以使用Add方法:

    something.Add("testKey", 123);
    
  • 取值操作(对应Map.get())
    如果你需要和JSget行为完全对齐:键不存在时不抛出异常,可以使用TryGetValue方法:

    // 等效于 const value = something.get('testKey'); 可自行处理键不存在的场景
    if (something.TryGetValue("testKey", out int value))
    {
        // 键存在,value为对应的值
    }
    else
    {
        // 键不存在,对应JS中get返回undefined的场景
    }
    

    如果你确定键一定存在,也可以直接用索引器取值:

    int value = something["testKey"];
    

    注意:该写法如果键不存在会抛出KeyNotFoundException。

  • 其他常用对等操作

    • 判断键是否存在(对应Map.has()):something.ContainsKey("testKey")
    • 删除键(对应Map.delete()):something.Remove("testKey")
    • 获取元素总数(对应Map.size):something.Count

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:06:03