Mar*_*mes 1 c# oop inheritance multiple-inheritance
"假设以下代码:
public class MultiplasHerancas
{
static GrandFather grandFather = new GrandFather();
static Father father = new Father();
static Child child = new Child();
public static void Test()
{
grandFather.WhoAreYou();
father.WhoAreYou();
child.WhoAreYou();
GrandFather anotherGrandFather = (GrandFather)child;
anotherGrandFather.WhoAreYou(); // Writes "I am a child"
}
}
public class GrandFather
{
public virtual void WhoAreYou()
{
Console.WriteLine("I am a GrandFather");
}
}
public class Father: GrandFather
{
public override void WhoAreYou()
{
Console.WriteLine("I am a Father");
}
}
public class Child : Father
{
public override void WhoAreYou()
{
Console.WriteLine("I am a Child");
}
}
Run Code Online (Sandbox Code Playgroud)
我想从"孩子"对象打印"我是祖父".
我怎么能做Child对象在"base.base"类上执行一个方法?我知道我可以做它执行基本方法(它将打印"我是一个父亲"),但我想打印"我是一个盛大的父亲"!如果有办法做到这一点,是否在OOP设计中推荐?
注意:我不使用/将使用此方法,我只是想加强知识继承.
这只能使用方法隐藏 -
public class GrandFather
{
public virtual void WhoAreYou()
{
Console.WriteLine("I am a GrandFather");
}
}
public class Father : GrandFather
{
public new void WhoAreYou()
{
Console.WriteLine("I am a Father");
}
}
public class Child : Father
{
public new void WhoAreYou()
{
Console.WriteLine("I am a Child");
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为 -
Child child = new Child();
((GrandFather)child).WhoAreYou();
Run Code Online (Sandbox Code Playgroud)
使用new关键字hides the inherited member of base class in derived class.