<分区>
据我了解,默认情况下字典中的键检查是区分大小写的,但看起来,至少在我的软件中,情况并非如此。为了对 TryGetValue 和 Contains 进行区分大小写的键检查,我必须按如下方式构建我的字典:
Dictionary<string, string> a = new Dictionary<string,string>(StringComparer.Ordinal);
那我错了吗?默认情况下字典不区分大小写吗?
<分区>
据我了解,默认情况下字典中的键检查是区分大小写的,但看起来,至少在我的软件中,情况并非如此。为了对 TryGetValue 和 Contains 进行区分大小写的键检查,我必须按如下方式构建我的字典:
Dictionary<string, string> a = new Dictionary<string,string>(StringComparer.Ordinal);
那我错了吗?默认情况下字典不区分大小写吗?
最佳答案
不, Dictionary<string, string>
默认情况下不区分大小写。
这可以通过这个小应用程序轻松显示:
using System;
using System.Collections.Generic;
public class MainClass
{
public static void Main(string[] args)
{
var newDict = new Dictionary<string, string>();
newDict.Add("a", "x");
Console.WriteLine(newDict.ContainsKey("a"));
Console.WriteLine(newDict.ContainsKey("A"));
newDict.Add("A", "y");
Console.WriteLine(newDict.ContainsKey("a"));
Console.WriteLine(newDict.ContainsKey("A"));
Console.WriteLine(newDict.Count);
}
}
这个输出:
True
False
True
True
2
解释:
a
已添加。ContainsKey
用于检查键是否为a
和 A
被发现。只有前者是。Add
用于添加键 A
.它不会提示,即它认为 key 不存在。Count
用于检查字典条目的总数并正确输出 2
, 即 A
和 a
.关于c# - 为什么我的 Dictionary<string, string> 默认不区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23404739/
相关文章:
c# - 在多线程应用程序中使用 MessageBox 显示异常信息
linux - Node.js Express 静态 Assets 的大小写敏感性
c# - MVC2 Html.ValidationMessageFor : add htmlAttributes but keep the default message
c# - Command.CanExecute 触发后 CommandParameter 绑定(bind)解析
swift - 键 : String value:Array in swift 的扩展字典
python - 为什么 python dict.update() 不返回对象?