gpt4 book ai didi

c# - 为什么要调用基类?

转载 作者:太空狗 更新时间:2023-10-29 18:02:51 24 4
gpt4 key购买 nike

这是我的情况:

interface Icontainer{
string name();
}

abstract class fuzzyContainer : Icontainer{
string name(){
return "Fuzzy Container";
}
}

class specialContainer: fuzzyContainer{
string name(){
return base.name() + " Special Container";
}
}


Icontainer cont = new SpecialContainer();
cont.name(); // I expected "Fuzzy Container Special Container" as the output.

当我如上所述运行我的代码时,输​​出只是“Fuzzy Container”。我在这里错过了什么?有没有更好的方法来获得预期的结果?

最佳答案

如果您在 specialContainer 中创建 name() virtual 然后 override,您将获得预期的行为。

public interface Icontainer
{
string name();
}

public abstract class fuzzyContainer : Icontainer
{
public virtual string name()
{
return "Fuzzy Container";
}
}

public class specialContainer : fuzzyContainer
{
public override string name()
{
return base.name() + " Special Container";
}
}

关于c# - 为什么要调用基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2746620/

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