【发布时间】:2016-05-31 15:02:56
【问题描述】:
以下代码给出不同的输出。谁能解释一下为什么?
代码如下所示。结果集显示在其下方。
我已经在 Enterprise VS 2015 Update 2 上编译了代码。
我在 Win7 上运行它。
请注意,我在两个示例中都使用了阴影(隐藏)。这个问题不涉及阴影与覆盖的使用。问题是“为什么阴影会导致两个不同的输出?”
这是编译和运行的代码,并为调用对象的两种不同方法给出不同的结果:
using System;
namespace InheritanceApplication
{
internal class FooBarParent
{
public void Display()
{
Console.WriteLine("FooBarParent::Display");
}
}
internal class FooBarSon : FooBarParent
{
public new void Display()
{
Console.WriteLine("FooBarSon::Display");
}
}
internal class FooBarDaughter : FooBarParent
{
public new void Display()
{
Console.WriteLine("FooBarDaughter::Display");
}
}
internal class Example
{
public static void Main()
{
GoodBar();
FooBar();
}
public static void GoodBar()
{
Console.WriteLine("Example::Goodbar ...");
var fooBarParent = new FooBarParent();
fooBarParent.Display();
var fooBarSon = new FooBarSon();
fooBarSon.Display();
var fooBarDaughter = new FooBarDaughter();
fooBarDaughter.Display();
}
public static void FooBar()
{
Console.WriteLine();
Console.WriteLine("Example::Foobar ...");
var fooBarFamily = new FooBarParent();
fooBarFamily.Display();
fooBarFamily = new FooBarSon();
fooBarFamily.Display();
fooBarFamily = new FooBarDaughter();
fooBarFamily.Display();
}
}
}
这是结果集:
Example::Goodbar ...
FooBarParent::Display
FooBarSon::Display
FooBarDaughter::Display
Example::Foobar ...
FooBarParent::Display
FooBarParent::Display
FooBarParent::Display
【问题讨论】:
-
你知道什么是
virtual,你什么时候“有”使用它?并且使用var是模棱两可的 -
看看这个SO Question。
-
在
FooBar中,fooBarFamily是静态类型作为FooBarParent的一个实例。因此,当您将其设置为FooBarSon的实例时,它不会改变。所以它仍然会调用FooBarParent.Display()。 -
我拒绝这是对 Ivan Stoev 在 C# 中阴影和覆盖之间的区别的重复问题? 5 个答案。
-
请注意,我最好使用虚拟。但是,我不是在问“如何最好地编写代码”。我在问,为什么这段代码会给出不同的输出?
标签: c# inheritance