簡體   English   中英

帶有 StringComparer.InvariantCultureIgnoreCase 的 C# 字典在嘗試添加不區分大小寫的鍵時出錯

[英]C# Dictionary with StringComparer.InvariantCultureIgnoreCase giving error while trying to add case insensitive key

嘗試代碼,

using System;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        Dictionary<string, object> paramList = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
        paramList.Add("LastUpdatedByUserName", "123");
        paramList.Add("LastUpdatedbyUserName", "124");
        
        Console.WriteLine(paramList["LastUpdatedbyUserName"]);
    }
}

這給了我一個錯誤說,

Run-time exception (line 11): An item with the same key has already been added.
  • 在 Dictionary 中,key 不能為 null,但 value 可以。
  • 在字典中,鍵必須是唯一的。 如果您嘗試使用重復鍵,則不允許使用重復鍵,那么編譯器將在您獲得時拋出異常。

當心,在您的例子還有的按鍵時LASTUPDATED略有區別B yUserNameLASTUPDATED b yUserName

構造函數需要一個IEqualityComparer ,它告訴字典如何比較鍵。

StringComparer.InvariantCultureIgnoreCase為您提供了一個IEqualityComparer實例,它以不區分大小寫的方式比較字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM