为什么我不能在C#中定义一个case-insensitve Dictionary? [英] Why can't I define a case-insensitve Dictionary in C#?

查看:152
本文介绍了为什么我不能在C#中定义一个case-insensitve Dictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个C#/ WPF代码:

This C#/WPF code:

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);

        }
    }
}

给我错误


最好的重载方法匹配
'System.Collections.Generic.Dictionary .Dictionary(System.Collections.Generic.IDictionary)'
有一些无效的参数

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

但是我发现这个代码示例 everywhere 这里 这里

Yet I find this code example everywhere such as here and here.

如何定义一个字典,其键是不区分大小写?

推荐答案

您正在尝试使用 StringComparison ,这是一个枚举。您应该使用 StringComparer.InvariantCultureIgnoreCase 代替 - 这是一个返回 StringComparer ,它实现 的IEqualityComparer<串GT; 。然后,您最终会调用 字典<,> 构造函数重载接受一个 IEqualityComparer< TKey> ,它可以用来检查相等性并生成哈希代码。

You're trying to using StringComparison, which is an enum. You should be using StringComparer.InvariantCultureIgnoreCase instead - that's a property returning a StringComparer, which implements IEqualityComparer<string>. You'll then end up calling the Dictionary<,> constructor overload accepting an IEqualityComparer<TKey> which it can use to check for equality and generate hash codes.

这篇关于为什么我不能在C#中定义一个case-insensitve Dictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆