Possible Duplicate:
How to call base.base.method()?
I have some trouble with Inheritance in C#. I've sketched three classes: A
, B
and C
. C
inherits from B
and B
from A
. Now the B
class calls base.Method1
and works fine but I can't call A.method1
from the C
class. If I call base.Method1
from C
obviously that method will be method1
of B
. Any advice?
P.S. in A
class there are some fields marked private so you can access them only
class A
{
private instance;
public virtual void Method1 ()
{
instance = this;
do something;
}
}
class B : A
{
public override void Method1()
{
base.Method1();
do something;
}
}
class C : B
{
public override void Method1 ()
{
//need A Method1 then do something
}
}
But, since you have overridden the parent method how can you still call it? You can use super. method() to force the parent's method to be called.
In Java, a class cannot directly access the grandparent's members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor's member in the inheritance hierarchy. In Java, we can access grandparent's members only through the parent class.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
This is a feature of C#. If you wish to expose this method to class C, consider refactoring A like so:
class A
{
private instance;
public virtual void Method1 ()
{
AMethod1();
}
protected void AMethod1()
{
instance = this;
do something;
}
}
This will enable you to call this method from within C:
class C : B
{
public override void Method1 ()
{
AMethod1();
// do something;
}
}
It is not possible to do this in C#, thought its possible to do this via IL.
For your case, you may do something like this:
class A
{
private int instance;
public virtual void Method1()
{
Method1Impl();
}
protected void Method1Impl()
{
}
}
Now you can call A.Method1Impl
from your C class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With