gpt4 book ai didi

.net - KeyedCollection字符串不区分大小写

转载 作者:行者123 更新时间:2023-12-04 07:56:36 25 4
gpt4 key购买 nike

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

    关于.net - KeyedCollection字符串不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12151642/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com