c# - 为什么我不能在 C# 中定义不区分大小写的字典?

标签 c# dictionary case-insensitive

此 C#/WPF 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestDict28342343
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            Dictionary<string, string> variableNamesAndValues = 
                new Dictionary<string, string>(StringComparison.InvariantCultureIgnoreCase);

        }
    }
}

给我错误:

The best overloaded method match for 'System.Collections.Generic.Dictionary.Dictionary(System.Collections.Generic.IDictionary)' has some invalid arguments

然而我发现此代码示例无处不在,例如 here here .

如何定义键不区分大小写的字典?

最佳答案

您正在尝试使用 StringComparison ,这是一个枚举。你应该使用 StringComparer.InvariantCultureIgnoreCase 相反 - 这是一个返回 StringComparer 的属性, 它实现了 IEqualityComparer<string> .然后你最终会调用 Dictionary<,> constructor overload accepting an IEqualityComparer<TKey> 它可以用来检查相等性并生成哈希码。

关于c# - 为什么我不能在 C# 中定义不区分大小写的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2491403/

相关文章:

java - 如何从 "new map()"HQL 生成的列表中获取值?

resources - 带有标题 munge 的 puppet 资源命令

sql - 如何更改 sqlite3 数据库的排序规则以不区分大小写排序?

c# - 类型 xxxx 不应使用 xmlinclude 或 soapinclude

c# - 有没有比这更好的方法来将函数注入(inject) Unity 中的对象?

c++ - map 中任何类型的值

python - 提高包含 3000 多个条目的字典的性能

php - 不区分大小写的字符串比较

c# - native 类是否可以使用 .NET 事件?

c# - 对返回类型使用 ReadOnlyCollection<T> 与 List<T> 与数组