尝试按照文档进行操作,但我无法使其正常工作。有一个包含 key 字符串的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

最佳答案

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

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

StringComparer class具有一些默认的IEqualityComparer<T>实现,这些实现取决于存储的数据类型:
  • StringComparer.Ordinal StringComparer.OrdinalIgnoreCase -在使用机器可读的字符串时使用,而不是输入或显示给用户的字符串。
  • StringComparer.InvariantCulture StringComparer.CultureInvariantIgnoreCase -当您使用不会显示在UI上但对文化敏感并且在不同文化中可能相同的字符串时使用。
  • StringComparer.CurrentCulture StringComparer.CurrentCultureIgnoreCase -用于特定于当前区域性的字符串,例如在收集用户输入时。

  • 如果您需要一种除当前文化以外的其他文化的StringComparer,则可以调用静态 Create method为特定 StringComparer 创建一个CultureInfo

    10-05 18:17