开发者

Can't see parent's methods in derived class

I'm trying to extend a class, then use a method from base class, but i can't see it.

开发者_运维知识库

My Code:

class A {
    protected void Foo(){}
}

class B : A {}

class C{
    void Bar(){
         B b = new B();
         b.Foo();
    }
}

How could i use b.Foo in C?


You can't. Foo is a protected member function of class A, and as such can only be used from within class A, or from within a class that inherits from it.

class A 
{
   protected int x() {}
}

class B : A 
{
   void F() 
   {
      A a = new A();  
      B b = new B();  
      a.x();   // Error
      b.x();   // OK
   }
}


You can only see protected method from the within the descendant classes.

C doesn't inherit from B so, by definition, it cannot see its protected methods.


You need to mark Foo with the public modifier rather than protected because C does not inherit B; it "uses" B.

See here for more information.


Make it public. Foo() will only be visible to A and its derived classes (like 'B'). C is not a derived class of A.


You must make the method Foo public.

class A {
    public void Foo() {}
}

class B : A {}

class C {
    void Bar(){
         B b = new B();
         b.Foo(); // Works
    }
}


Because Foo is protected it's can't be seen to anything except derived classes.

To expose it you need to do:

class A 
{
    protected void Foo(){}
}

class B : A 
{
    public new void Foo()
    {
        base.Foo()
    }
}

Other answers have touched on this but none mention the use of the new keyword to expose the method with the same name, but different accessibility.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜