哈希码(哈希值)是C#中的一个重要概念,它是通过哈希函数对对象进行特征提取而产生的一个数值。哈希码主要应用于集合,用于快速地比较集合中的元素,如数组、字典和列表等。C# 计算对象的哈希码主要通过以下步骤进行:
C# 提供了一系列默认的哈希函数,如 GetHashCode()
和 Object.GetHashCode()
。前者被所有类型继承,后者被所有可映射对象继承。这些哈希函数对对象的属性、方法列表等进行运算,以产生哈希码。
示例代码:
public class A
{
public int Field1 { get; set; }
public string Field2 { get; set; }
public override int GetHashCode()
{
// 如果Field1和Field2的取值不同,那么计算结果为哈希码的一部分
return Field1.GetHashCode() ^ Field2.GetHashCode();
}
}
接下来,C# 对对象进行特征提取。哈希函数返回一个数值,这个数值通常是唯一的(在大多数情况下)。C# 在哈希函数之上提供一个更复杂、更具体的哈希函数 GetHashCode(T obj)
,可以对对象进行更全面的特征提取。这种哈希函数由开发者根据对象的具体属性手动定义。以下是一个使用 GetHashCode(T obj)
示例的 IMyInterface
接口:
示例代码:
[AttributeUsage(AttributeTargets.Class)]
public class MyInterfaceAttribute : Attribute
{
public string InterfaceName { get; }
public MyInterfaceAttribute(string interfaceName)
{
InterfaceName = interfaceName;
}
}
[MyInterface("SomeInterface")]
public interface IMyInterface<T> where T : System.IComparable
{
T Sum()
{
int x = 0, y = 0;
foreach (var item in this)
{
x += (item as T);
y++;
}
return x > 0 ? (T)(double)x / y : default(T);
}
System.IStructuralEquatable IMyInterface<T>.Equals(object obj, System.IEqualityComparer comparer)
{
if (obj == null) return false;
return type.Equals(obj.GetType(), comparer);
}
System.IComparer IMyInterface<T>.CompareTo(object obj)
{
if (obj == null) return 1;
if (!(obj is T)) throw new ArgumentException("Type mismatch");
T current = obj as T;
T other = current;
for (int i = 0; i< type.GetPropertyCount(); i++)
{
PropertyInfo pinfo = type.GetProperty(type.GetPropertyName(i));
other = pinfo.GetValue(current);
current = pinfo.GetValue(obj);
}
return other.CompareTo(current);
}
private System.Type type;
public IMyInterface(Type type)
{
this.type = type;
}
}
class MyClass : SomeInterfaceImplementingIMyInterface<int>, SomeOtherInterfaceImplementingIMyInterface<decimal>
{
private static MyClass Default { get; } = new MyClass(30);
public override int GetHashCode()
{
// 区分两个不同对象,这里只提取一个属性作为区分依据
return Default.InterfaceImplementingIMyInterfaceAttribute.InterfaceName[0].ToString().GetHashCode(System.NumberStyles.Integer);
}
}
以上就是一个计算对象哈希码的C# 代码实现。
领取专属 10元无门槛券
手把手带您无忧上云