我试着按照文档操作,但我不能让它工作。有一个包含密钥字符串的KeyedCollection。
如何在KeyedCollection中使字符串键不区分大小写?
可以只在ctor中传递StringComparer.OrdinalIgnoreCase。
private static WordDefKeyed wordDefKeyed = new WordDefKeyed(StringComparer.OrdinalIgnoreCase); // this fails
public class WordDefKeyed : KeyedCollection<string, WordDef>
{
// The parameterless constructor of the base class creates a
// KeyedCollection with an internal dictionary. For this code
// example, no other constructors are exposed.
//
public WordDefKeyed() : base() { }
public WordDefKeyed(IEqualityComparer<string> comparer)
: base(comparer)
{
// what do I do here???????
}
// This is the only method that absolutely must be overridden,
// because without it the KeyedCollection cannot extract the
// keys from the items. The input parameter type is the
// second generic type argument, in this case OrderItem, and
// the return value type is the first generic type argument,
// in this case int.
//
protected override string GetKeyForItem(WordDef item)
{
// In this example, the key is the part number.
return item.Word;
}
}
private static Dictionary<string, int> stemDef = new Dictionary<string, int(StringComparer.OrdinalIgnoreCase); // this works this is what I want for KeyedCollection发布于 2012-08-28 11:27:38
如果您希望默认情况下类型WordDefKeyed不区分大小写,那么默认的无参数构造函数应该向其传递一个IEqualityComparer实例,如下所示:
public WordDefKeyed() : base(StringComparer.OrdinalIgnoreCase) { }StringComparer class具有一些常用的默认IEqualityComparer<T>实现,具体取决于您要存储的数据类型:
StringComparer.Ordinal和StringComparer.CultureInvariantIgnoreCase -当您使用机器可读字符串时使用,而不是输入或显示到cultures.StringComparer.CurrentCulture和StringComparer.OrdinalIgnoreCase中的字符串-当您使用不会显示给UI但对区域性敏感且在cultures.StringComparer.CurrentCulture和StringComparer.CurrentCultureIgnoreCase中可能相同的字符串时使用-用于特定于当前区域性的字符串,例如在收集用户输入时。如果需要当前区域性以外的区域性的StringComparer,则可以调用静态Create method为特定CultureInfo创建StringComparer。
https://stackoverflow.com/questions/12151642
复制相似问题