How to hide a method, which is part of an interface implementation within a base class, from classes that derive from the base class?

StackOverflow https://stackoverflow.com/questions/23562815

I have the following structure:

public class Foo : FooBaseNamespace.FooBase
{
    public Foo()
    {
        Register("abc");
    }
}

public class FooBase : IFoo
{
    public FooBase()
    {

    }

    public void Register(string id)
    {

    }
}

public interface IFoo
{
    void Register(string id);
}

Please note that FooBase and IFoo reside in namespace FooNamespace but Foo resides in a different namespace but has access to FooNameSpace.

My question is, can I adjust the code so that method Register(string id) is hidden from any classes that derive from FooBase?

Thanks

有帮助吗?

解决方案

I really don't understand why you're implementing IFoo if you want to then hide that, and I think your modelling is not really correct.

See the Liskov Substitution Principle for more info.

Substitutability is a principle in object-oriented programming. It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

You could contain an IFoo implementation within your FooBase object (i.e. use composition) and delegate e.g.

public class FooBase {
   private IFoo hiddenFoo;
}

or perhaps use multiple interfaces e.g. IRegisterable alongside IFoo, where IRegisterable provides the Register() method and IFoo provides everything else. You can selectively reference IRegisterable as required.

Separating your interface definitions into interfaces providing distinct functions is a powerful means to giving objects different functionality depending on how they're referenced (e.g. one DAO can implement both IReadable and IWriteable and that functionality is exposed separately to different clients)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top