pap*_*zzo 8 .net string-comparison iequalitycomparer
尝试遵循文档,我无法使其工作.使用键字符串键入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
Run Code Online (Sandbox Code Playgroud)
如果您希望WordDefKeyed默认情况下您的类型不区分大小写,那么您的默认无参数构造函数应该将IEqualityComparer<string>实例传递给它,如下所示:
public WordDefKeyed() : base(StringComparer.OrdinalIgnoreCase) { }
Run Code Online (Sandbox Code Playgroud)
该StringComparer班有一些默认的IEqualityComparer<T>通常使用的取决于你存储数据的类型实现:
StringComparer.Ordinal和StringComparer.OrdinalIgnoreCase-当你使用机器可读的字符串,而不是被输入或向用户显示的字符串使用.
StringComparer.InvariantCulture和StringComparer.CultureInvariantIgnoreCase-当你使用,不会显示给用户界面字符串,但对文化敏感,可能是跨文化一样使用.
StringComparer.CurrentCulture和StringComparer.CurrentCultureIgnoreCase- 用于特定于当前文化的字符串,例如当您收集用户输入时.
如果你需要StringComparer一个文化等一个比它是与当前的文化,那么你可以调用静态Create方法来创建StringComparer特定CultureInfo.