为什么我不能在 C# 中定义不区分大小写的字典?
此 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);
}
}
}
给我错误:
最佳重载方法匹配 'System.Collections.Generic.Dictionary.Dictionary(System.Collections.Generic.IDictionary)' 有一些无效参数
如何定义键不区分大小写的字典?
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);
}
}
}
gives me the error:
The best overloaded method match for
'System.Collections.Generic.Dictionary.Dictionary(System.Collections.Generic.IDictionary)'
has some invalid arguments
Yet I find this code example everywhere such as here and here.
How can I define a Dictionary whose keys are case-insensitve?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试使用
StringComparison
,这是一个枚举。您应该使用StringComparer.InvariantCultureIgnoreCase
< /a> 相反 - 这是一个返回StringComparer
,它实现IEqualityComparer
。然后,您最终将调用Dictionary< ;,>
构造函数重载接受IEqualityComparer
,可用于检查相等性并生成哈希码。You're trying to using
StringComparison
, which is an enum. You should be usingStringComparer.InvariantCultureIgnoreCase
instead - that's a property returning aStringComparer
, which implementsIEqualityComparer<string>
. You'll then end up calling theDictionary<,>
constructor overload accepting anIEqualityComparer<TKey>
which it can use to check for equality and generate hash codes.传递 StringComparer.InvariantCultureIgnoreCase。注意 StringComparer 而不是 StringComparison。
更一般地,的“固定”实现,而您需要的是后者。
Dictionary
构造函数可以采用IComparer
类型的参数。正如 Jon 指出的,StringComparison 是一个枚举。但是 StringComparer 提供了一些 IComparerPass StringComparer.InvariantCultureIgnoreCase. Note StringComparer not StringComparison.
More generally, the
Dictionary<TKey, TValue>
constructor can take an argument of typeIComparer<TKey>
. As Jon notes, StringComparison is an enum. But StringComparer provides some "canned" implementation ofIComparer<string>
, and it's the latter that you need.这在我的电脑上有效:
This works on my computer: