gpt4 book ai didi

c# - C#中的继承误区

转载 作者:太空狗 更新时间:2023-10-29 22:13:52 24 4
gpt4 key购买 nike

我想了解继承在 C# 中的工作方式。基本上,我有一个具有简单函数 sayIt 的基类 Base。该函数使用在子类中重新定义的属性“i”。在这里,它被重新定义为从 0 开始的 1。当我运行这个程序时,我得到“0”作为输出而不是我所期望的“1”(因为在 python 中我会得到 1)。谁能解释为什么,更重要的是,这是否是 C# 支持的模式?

class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Console.WriteLine(d.sayIt());
Console.ReadLine();
}
}

class Base
{
int _i = 0;
public int i
{
get { return _i; }

}

public String sayIt()
{
return Convert.ToString(this.i);
}
}

class Derived : Base
{
int _i = 1;
public new int i
{
get { return _i; }
}
}

最佳答案

  1. Base 类中将属性标记为 virtual

  2. Derived 类中的属性旁边的 new 替换为 override

1. 是必需的,因为默认情况下,成员在 c# 中是非虚拟的。和 2. 是必要的,因为使用 new 会破坏 virtual 解析 channel ,这不是您想要的。

MSDN 上有一篇关于newoverride 的好文章:Knowing When to Use Override and New Keywords (C# Programming Guide) .

The override modifier extends the base class method, and the new modifier hides it.

关于c# - C#中的继承误区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20962003/

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