Force方法从base调用子类的新方法

时间:2018-05-04 23:10:40

标签: c# class methods public protected

我的理解是,子类的行为与父类完全相同,除了其他方法或使用overrideclass BIG protected void Output(string text = "") Console.WriteLine("BIG - " + text); public void CallingOutput() Output("Outputting..."); class SMALL:BIG public new void Output(string text = "") Console.WriteLine("SMALL - " + text); class Program static void Main(string[] args) SMALL foo = new SMALL(); 关键字“重写”的方法。显然,这不正确。

请参阅下面的代码(为了便于阅读,删除了括号)

BIG.Output(string)

我已经知道我可以使用new关键字隐藏SMALL中的>> foo.Output("Outputting...") SMALL - Outputting... 。直接打电话时,效果很好。

class SMALL:BIG

这与我的理解相冲突。我认为定义class SMALL与定义class SMALL public void Output(string text = "") Console.WriteLine("SMALL - " + text); public void CallingOutput() Output("Outputting..."); 并从BIG复制粘贴所有方法完全相同。简而言之,我认为上面的SMALL类等同于:

>> foo.CallingOutput()
BIG - Outputting...

显然这是不正确的,因为

Output(string)

当间接调用时,它仍在使用BIG中的原始foo.CallingOutput()

这样做的正确方法是"SMALL - Outputting..."输出

BIG

假设我无法访问CallingOutput()并且不允许进行任何更改。我也不想隐藏CallingOutput(),因为这基本上是重写了类。 (是的,隐藏C++使其有效)

我在发布之前做了一些搜索,并在I am travelling from London to New York. I am flying to Sydney from Singapore. 中找到了类似的问题。但是,答案是不可能的。

  1. 我不相信。这么强大的语言,然而,没有办法告诉编译器哪个方法是哪个。
  2. 这是一种不同的语言,所以这篇文章是允许的,因为它不能被视为重复。

2 个答案:

答案 0 :(得分:0)

new替换为override,如下所示:

class SMALL:BIG
public override void Output(string text = "")
    Console.WriteLine("SMALL - " + text);

答案 1 :(得分:0)

创建一个垫片

除非设计为被覆盖,否则您无法修改或覆盖现有类中的任何内容。这是设计的。

话虽这么说,你可以创造一个新的" shim" (pass-through)类与原始类完全相同,但成员被声明为virtual。这是通过使用newvirtual修饰符来完成的。

获得垫片类后,您可以按正常方式覆盖该方法。例如:

class Big
{
    public void Output(string text) { Console.WriteLine("Big - {0}", text); }

    public void CallingOutput()
    {
        Output("Outputting...");
    }
}

class Shim : Big
{
    public new virtual void Output(string text) { base.Output(text); }

    public void CallingOutput()
    {
        Output("Outputting...");
    }
}

现在你有了一个允许你想要的Shim类。所以将它子类化(而不是Big)并看看会发生什么:

class Small : Shim
{
    public override void Output(string text) { Console.WriteLine("Small - {0}", text); }
}

测试它:

Shim s = new Shim();
s.CallingOutput();   //Original behavior

Shim s = new Small();
s.CallingOutput();   //Overridden behavior

输出:

Big - Outputting...
Small - Outputting...

Example on DotNetFiddle

相关问题