Force child class to override function of ancestor

2020-02-06 07:26发布

I am writing an algorithm which requires the user to create his own class which inherits from a class defined by me. However, the algorithm requires the user to override the Equals and GetHashCode functions from the C# standard libraries.

Can I force the class inherited from my class to implement the GetHashCode and Equals functions?

public abstract int GetHashCode();

Writing this in my base class is not an option, as my base class inherits GetHashCode from it's parent, where it is implemented already.

3条回答
Viruses.
2楼-- · 2020-02-06 07:33

You can create 2 new methods that will be abstract and will be called from GetHashCode and Equals your class.

Example:

public abstract ParentClass {
    public abstract int MyGetHashCode();

    public override int GetHashCode(){
        return MyGetHashCode();
    }

    // same thing for Equals
}
查看更多
Summer. ? 凉城
3楼-- · 2020-02-06 07:40

This is what you're looking for. Since your class is abstract you can pretty much do this without any problem.

public abstract override int GetHashCode();

This despite of it derived from some other class, this makes your sub class must override this method.

查看更多
叛逆
4楼-- · 2020-02-06 07:40

In your class:

public override bool Equals(object obj)
{
    throw new System.NotImplementedException();
}

public override int GetHashCode()
{
    throw new System.NotImplementedException();
}

This means that if they don't override it the function will fail by exception. This forces them to override it to get it to work.

查看更多
登录 后发表回答