如何在Castle.Core 中实现IProxyGenerationHook 的类中实现Equals 和GetHashCode 的覆盖方法?

问题描述

阅读 Castle.Core 文档,在 this link 中,他们建议总是覆盖 EqualsGetHashCode 方法实现 IproxygenerationHook 的类。

我有一个名为 MiHook 的类实现了这样的接口,但是这个类没有状态。所以,我的问题是,如果我有一个无状态类,我应该如何覆盖这两个方法

public class MiHook : IproxygenerationHook {
    public void MethodsInspected() { }

    public void NonProxyableMemberNotification(Type type,MemberInfo memberInfo) { }

    public bool ShouldInterceptMethod(Type type,MethodInfo methodInfo) {
        return methodInfo.Name == nameof(IFoo.Bar);
    }

    // Should I implement both methods like this?
    public override bool Equals(object? obj) => base.Equals(obj);
    public override int GetHashCode() => base.GetHashCode();
}

解决方法

我不确定您所说的无状态类是什么意思 - 您的意思是它没有任何字段吗? what is a stateless class?

您示例中的基本实现与根本不覆盖一样好。你需要问自己一个问题:

什么使 MiHook 类型的两个对象相等?

根据您对 ShouldInterceptMethod 的实现判断,它是 Type(IFoo.Bar)。如果是这种情况,我会选择 IFoo.Bar - “依赖”覆盖:

   public class MiHook : IProxyGenerationHook
    {
        public void MethodsInspected() { }
        public void NonProxyableMemberNotification(Type type,MemberInfo memberInfo) { }
        public bool ShouldInterceptMethod(Type type,MethodInfo methodInfo)
        {
            return methodInfo.Name == nameof(IFoo.Bar);
        }
        public override bool Equals(object obj)
        {
            if (obj == null || obj.GetType() != this.GetType()) return false;
            return obj.GetHashCode() == this.GetHashCode();
        }
        public override int GetHashCode() => typeof(IFoo.Bar).GetHashCode();
    }

测试:

var mh1 = new MiHook<Foo.Bar>();
var mh2 = new MiHook<Foo.Bar>();
Console.WriteLine(mh1.Equals(mh2)); //True
//your implementation returns False
,

在 Glimpse 项目中,IProxyGenerationHook 也被覆盖。尽管它们仍然有一个私有字段用于覆盖 GetHashCode 和 Equals:

private IEnumerable<IAlternateMethod> methodImplementations;

这是指向包含方法 GetHashCode 和 Equals 的 source file 的链接。

也许它作为灵感来源很有用。