简体   繁体   中英

How to implement the override methods of Equals and GetHashCode in a class that implements IProxyGenerationHook in Castle.Core?

Reading the Castle.Core documentation, in this link , they recommend that always overriding the Equals and GetHashCode methods of the classes that implement IProxyGenerationHook .

I have a class called MiHook that implements such interface, but this class doesn't have state. So, my question is, how should I override those two methods if I have a stateless class?

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();
}

I'm not sure what do you mean by stateless class - do you mean that it doesn't have any fields? what is a stateless class?

Base implementation in your example is as good as not overriding at all. You need to ask yourself a question:

What makes two objects of type MiHook equal?

Judging by your implementation of ShouldInterceptMethod it is the Type( IFoo.Bar ). If that's the case, I would go for a IFoo.Bar - "dependent" override:

   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();
    }

To test it:

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

In the Glimpse project the IProxyGenerationHook is also overridden. Although they still have a private field that is used to override GetHashCode and Equals:

private IEnumerable<IAlternateMethod> methodImplementations;

Here is the link to the source file that contains the methods GetHashCode and Equals.

Maybe it is useful as source of inspiration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM