gpt4 book ai didi

c# - 从 "base.base"类调用方法?

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:53 29 4
gpt4 key购买 nike

“假设以下代码:

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");

}
}

我想从“ child ”对象打印“我是祖父”。

我如何让子对象在“base.base”类上执行方法?我知道我可以执行基本方法(它会打印“我是父亲”),但我想打印“我是祖父”!如果有办法做到这一点,是否在 OOP 设计中推荐?

注意:我不使用/将要使用这种方法,我只是想加强知识传承。

最佳答案

这只能使用 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关键字在派生类中隐藏基类的继承成员

关于c# - 从 "base.base"类调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281292/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com