Hide a base class method in a generic derived class

后端 未结 2 1709
别跟我提以往
别跟我提以往 2021-01-19 06:21

I have a base class like this:

class FooBase
{
    public bool Do(int p) { /* Return stuff. */ }
}

And a child class like this:

<         


        
2条回答
  •  借酒劲吻你
    2021-01-19 06:56

    but if he creates a Foo object called "fooInt", he can only call the Do method of the derived class.

    No, that's not true. If the declared type of the variable is FooBase, it will still call the FooBase method. You're not really preventing access to FooBase.Do - you're just hiding it.

    FooBase foo = new Foo();
    foo.Do(5); // This will still call FooBase.Do
    

    Full sample code to show that:

    using System;
    
    class FooBase
    {
        public bool Do(int p) { return false; }
    }
    
    class Foo : FooBase
    {
        public bool Do(T p) { return true; }
    }
    
    class Test
    {
        static void Main()
        {
            FooBase foo1 = new Foo();
            Console.WriteLine(foo1.Do(10)); // False
    
            Foo foo2 = new Foo();
            Console.WriteLine(foo2.Do(10)); // True
        }
    }
    

    That's why I want to hide the Do method of the FooBase in Foo.

    You need to think about Liskov's Substitutability Principle.

    Either Foo shouldn't derive from FooBase (use composition instead of inheritance) or FooBase.Do shouldn't be visible (e.g. make it protected).

提交回复
热议问题