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

Edw*_*uay 8 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);

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

给我错误:

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

然而,我发现这个代码例子比比皆是,如在这里这里.

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

Jon*_*eet 20

你正在尝试使用StringComparison,这是一个枚举.你应该使用StringComparer.InvariantCultureIgnoreCase- 这是一个返回a的属性StringComparer,它实现了IEqualityComparer<string>.然后,您将最终调用Dictionary<,>构造函数重载,接受IEqualityComparer<TKey>可用于检查相等性并生成哈希码的内容.


Hen*_*man 8

更改

StringComparison.InvariantCultureIgnoreCase
Run Code Online (Sandbox Code Playgroud)

 StringComparer.InvariantCultureIgnoreCase
Run Code Online (Sandbox Code Playgroud)