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
4

1 回答 1

9

如果您希望您的类型WordDefKeyed默认不区分大小写,那么您的默认无参数构造函数应该将一个IEqualityComparer<string>实例传递给它,如下所示:

public WordDefKeyed() : base(StringComparer.OrdinalIgnoreCase) { }

该类具有一些常用的默认实现,具体取决于您存储的数据StringComparer类型IEqualityComparer<T>

如果您需要一种StringComparer文化不是当前文化,那么您可以调用静态Create方法StringComparer为特定的CultureInfo.

于 2012-08-28T03:27:37.623 回答