在C#中,要自定義哈希函數,首先需要創(chuàng)建一個實現IEqualityComparer<T>
接口的類
CustomHash
的類,實現IEqualityComparer<T>
接口:using System;
using System.Collections.Generic;
public class CustomHash<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
// 在這里實現你的相等性比較邏輯
throw new NotImplementedException();
}
public int GetHashCode(T obj)
{
// 在這里實現你的哈希函數
throw new NotImplementedException();
}
}
Equals
方法中實現相等性比較邏輯。例如,如果你要為字符串實現自定義哈希函數,可以比較兩個字符串是否相等:public bool Equals(T x, T y)
{
if (x is string strX && y is string strY)
{
return strX.Equals(strY, StringComparison.OrdinalIgnoreCase);
}
return false;
}
GetHashCode
方法中實現哈希函數。例如,對于字符串,可以將每個字符的ASCII值相加,然后乘以一個質數(例如31),以減少哈希沖突的可能性:public int GetHashCode(T obj)
{
if (obj is string str)
{
int hash = 0;
foreach (char c in str)
{
hash = hash * 31 + c;
}
return hash;
}
return 0;
}
Dictionary<TKey, TValue>
或HashSet<T>
:var customHash = new CustomHash<string>();
var dictionary = new Dictionary<string, int>(customHash);
dictionary.Add("hello", 1);
dictionary.Add("world", 2);
var hashSet = new HashSet<string>(customHash);
hashSet.Add("hello");
hashSet.Add("world");
這樣,你就可以在C#中使用自定義哈希函數了。請注意,自定義哈希函數可能會影響性能和內存使用,因此在實際應用中要謹慎使用。