C# 实现dictinnary 硬刚python nodejs

csharp
public static class DictionaryExtensions
{
    /// <summary>
    /// 安全地为字典中的键累加数值。如果键不存在,自动创建并设为初始值。
    /// </summary>
    public static void AddOrUpdateScore<TKey>(this Dictionary<TKey, int> dict, TKey key, int value)
    {
        if (dict.TryGetValue(key, out int current))
        {
            dict[key] = current + value;
        }
        else
        {
            dict[key] = value;
        }
    }
}


csharp
using System.Runtime.InteropServices;

// 如果不存在会自动初始化为 0,然后直接原地 +10,绝对不会崩溃
CollectionsMarshal.GetValueRefOrAddDefault(scores, "Alice", out _) += 10;

posted on 2026-09-26 23:39  漫思  阅读(7)  评论(0)    收藏  举报

导航