You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#多层继承场景下如何在控制台子类中重写上层父类的WriteLog方法

问题原因分析
  • 核心错误:你在Main方法中实例化的是DoMath父类对象,而非继承了DoMath的Program子类对象,多态生效的前提是用子类实例调用虚方法,这里根本没有用到Program类的实现,自然不会触发你写的重写逻辑。
  • 写法不规范点:DoMath中用new virtual修饰WriteLog相当于重新声明了一个同名的新虚方法,隐藏了LogThings基类的同名方法,虽然功能上也能支持后续重写,但用override直接重写基类虚方法更符合常规用法。
修正方案

基础类代码(无需修改)

public class LogThings
{
    public virtual void WriteLog(string value)
    {
        Console.WriteLine("This is the base in LogThings " + value);
    }
}

DoMath类优化(可选,仅规范写法)

把new virtual改为override,功能一致更符合重写逻辑:

public class DoMath : LogThings
{
    public double DoAddition(double a, double b)
    {
        double result = a + b;
        WriteLog(result.ToString());
        return result;
    }

    public override void WriteLog(string value)
    {
        Console.WriteLine("this is overriding the base in DoMath");
        base.WriteLog(value);
    }
}

控制台代码修改(核心修改)

将实例化对象改为Program子类即可:

class Program : DoMath
{
    static void Main(string[] args)
    {
        // 实例化子类Program,而非父类DoMath
        var m = new Program();
        m.DoAddition(1, 2);
      
        Console.ReadLine();
    }

    public override void WriteLog(string value)
    {
        // 可根据需求决定是否调用父类实现
        Console.WriteLine("this is overriding successfully.");
        // 需要保留父类逻辑就加下面这行
        // base.WriteLog(value);
    }
}
运行结果

修改后运行输出为:

this is overriding successfully.

如果保留了base.WriteLog(value)调用,输出为:

this is overriding successfully.
this is overriding the base in DoMath
This is the base in LogThings 3

补充说明

如果你无法修改DoMath类的现有实现,原本的new virtual写法也可以生效,只需要把Main方法里的new DoMath()改为new Program()即可达到重写效果。

内容的提问来源于stack exchange,提问作者8six7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:06:06