- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想了解继承在 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; }
}
}
最佳答案
在 Base
类中将属性标记为 virtual
将 Derived
类中的属性旁边的 new
替换为 override
。
1. 是必需的,因为默认情况下,成员在 c# 中是非虚拟的。和 2. 是必要的,因为使用 new
会破坏 virtual
解析 channel ,这不是您想要的。
MSDN 上有一篇关于new
和override
的好文章:Knowing When to Use Override and New Keywords (C# Programming Guide) .
The
override
modifier extends the base class method, and thenew
modifier hides it.
关于c# - C#中的继承误区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20962003/
我最近在做一个基于 TensorFlow 的 Udacity 深度学习类(class)。 .我有一个简单的 MNIST大约 92% 准确的程序: from tensorflow.examples.tu
意识不到误区的存在最为离谱; 01 生活中,职场上,游戏里,都少不了正面对喷过:意识太差; 在个人的认知中意识即思维,意识太差即思维中存在的误区比较多;
我是一名优秀的程序员,十分优秀!