键控集合字符串不区分大小写

9

我按照文档尝试了以下步骤,但无法使其正常工作。我有一个带有字符串键的KeyedCollection。

如何在KeyedCollection中使字符串键不区分大小写?

在Dictionary中,只需在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
1个回答

10
如果您希望您的类型 WordDefKeyed 默认情况下不区分大小写,那么您的默认无参构造函数应该将一个 IEqualityComparer<string> 实例传递给它,如下所示:
public WordDefKeyed() : base(StringComparer.OrdinalIgnoreCase) { }

StringComparer提供了一些默认的IEqualityComparer<T>实现,根据存储的数据类型不同,通常会使用以下几种:

如果您需要针对不是当前文化的特定文化创建StringComparer,则可以调用静态方法Create来创建一个特定CultureInfoStringComparer


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接