Dot-Net
KeyedCollection 字元串不區分大小寫
嘗試按照文件進行操作,但我無法使其工作。有一個帶有密鑰字元串的 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類型:IEqualityComparer<T>
StringComparer.Ordinal和StringComparer.OrdinalIgnoreCase- 當您使用機器可讀的字元串時使用,而不是輸入或顯示給使用者的字元串。StringComparer.InvariantCulture和StringComparer.CultureInvariantIgnoreCase- 當您使用不會向 UI 顯示但對文化敏感且跨文化可能相同的字元串時使用。StringComparer.CurrentCulture和StringComparer.CurrentCultureIgnoreCase- 用於特定於目前文化的字元串,例如當您收集使用者輸入時。如果您需要一種
StringComparer文化而不是目前文化,那麼您可以呼叫靜態Create方法來StringComparer為特定的CultureInfo.