“假定以下代码:
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");
}
}我想打印“我是一个祖父”从“孩子”对象。
如何在"base.base“类上执行子对象?我知道我可以执行基本方法(它会打印“我是一个父亲”),但我想打印“我是一个GrandFather"!如果有这样的方法,在OOP设计中推荐吗?
注:我不使用/将使用这种方法,我只是想加强知识继承。
发布于 2013-08-16 20:11:55
这只能使用Method Hiding -
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");
}
}就这样叫它-
Child child = new Child();
((GrandFather)child).WhoAreYou();使用new关键字hides the inherited member of base class in derived class。
发布于 2013-08-16 20:10:27
尝试使用“新”关键字而不是“覆盖”,并从方法中删除“虚拟”关键字;)
发布于 2017-01-10 06:19:58
这个程序在你运行时会出错。确保子对象将引用父类,然后使用引用类型转换调用方法Ex: child =new祖父();/这里我们正在创建引用父类的子实例。/((祖父)子).WhoAreYou();/*现在我们可以使用引用类型*/,否则它们在祖父类型转换下会出现错误。
https://stackoverflow.com/questions/18281292
复制相似问题