[C#.NET][VB.NET] 实践 IEqualityComparer 不分大小写 实践 IEqualityComparer ,不分大小写比较 //实践 public class InComparer : IEqualityComparer { CaseInsensitiveComparer myComparer = new CaseInsensitiveComparer(); public in
[C#.NET][VB.NET] 实践 IEqualityComparer 不分大小写
实践IEqualityComparer,不分大小写比较
//实践
public class InComparer : IEqualityComparer
{
CaseInsensitiveComparer myComparer = new CaseInsensitiveComparer();
public int GetHashCode(object obj)
{
return obj.ToString().ToLowerInvariant().GetHashCode();
}
public new bool Equals(object x, object y)
{
if (myComparer.Compare(x, y) == 0)
{
return true;
}
else
{
return false;
}
}
}
因为不分大小写所以First与first视为相同,程序在执行时会出现例外。
//引用类
Hashtable myData = new Hashtable(new InComparer());
myData.Add("First", "1st");
myData.Add("Senond", "2nd");
myData.Add("Third", "3rd");
myData.Add("Fourth", "4th");
myData.Add("Fifth", "5th");
myData.Add("first", "1st");
foreach (DictionaryEntry myEntry in myData)
{
Console.WriteLine("{0} = {1}", myEntry.Key, myEntry.Value);
}
当然也可以用CollectionsUtil类来不分大小写,这段程序看起来就短多了。
Hashtable myColl = CollectionsUtil.CreateCaseInsensitiveHashtable();
myColl.Add("A", "1234");
myColl.Add("a", "1234");
若有谬误,烦请告知,新手发帖请多包涵
2010~2017 C# 第四季
原文:大专栏 [C#.NET][VB.NET] 实践 IEqualityComparer 不分大小写