简体   繁体   中英

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

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 (ie, 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 (ie use composition) and delegate eg

public class FooBase {
   private IFoo hiddenFoo;
}

or perhaps use multiple interfaces eg 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 (eg one DAO can implement both IReadable and IWriteable and that functionality is exposed separately to different clients)

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