蓝色天空网mbsky.com · 知识 · 实践 · 创造C# · 本地阅读预览
教程 / 后端开发 / C#

C# 继承

讲解 C# 面向对象继承的 IS-A 语义、单类继承与多接口实现语法、protected 可见性与 base 基类初始化列表、接口继承链以及用类+接口组合替代类多重继承,并在本地 csc4 实测验证。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

继承思想与 IS-A 关系

继承(Inheritance)是面向对象程序设计实现代码复用与层次抽象的基石:允许基于已有类(称为基类/父类)定义新类(称为派生类/子类),直接复用既有字段与方法而不必从头重写。继承在建模上表达“属于(IS-A)”关系,例如哺乳动物属于动物、狗属于哺乳动物,因此狗也属于动物。

基类与派生类语法、protected 成员及 base 关键字

在 C# 中,一个类只能直接继承自唯一一个基类(不支持类的多重继承),但可以同时实现任意多个接口,语法上以冒号 `:` 分隔派生类与基类/接口列表(`class Derived : Base`)。派生类自动获得基类的非私有成员(`private` 成员虽仍存在于对象布局中但不可直接访问,而 `protected` 成员专供基类自身及派生类访问),并可通过 `base` 关键字显式调用基类方法或构造函数。本站实测 `DerivedDemo` 调用 `base.SomeMethod()` 以及 `SimpleRectangle : Shape` 读取 `protected` 字段 `width=5`、`height=7` 计算得总面积 `35`。

基类构造初始化顺序(: base(...))

因为派生类对象包含基类的全部状态,CLR 保证基类构造函数必须在派生类构造体之前执行。若基类仅提供有参构造函数,派生类须在构造函数签名后通过成员初始化列表 `: base(args)` 显式传递参数(如 `public Tabletop(double l, double w) : base(l, w)`),并在派生类方法中借 `base.DisplaySummary()` 复用基类逻辑(隐藏非虚同名方法时建议显式标注 `new` 修饰符消除编译警告)。本站实测 `new Tabletop(4.5, 7.5)` 严格按 `RectBase->Tabletop` 顺序初始化,面积 `33.75`、单价 70 对应总成本 `2362.5`。

接口继承与基于接口组合的多重继承

接口之间同样支持继承(且一个接口可继承多个基接口),派生接口将聚合全部基接口的成员声明且不得更改成员访问修饰符。任何实现派生接口(如 `IDerivedInterface : IBaseInterface`)的具体类都必须一并实现派生接口新增的 `Method2()` 与继承自基接口的 `Method1()`。本站实测 `MyInterfaceImpl` 同时满足两个接口视图并正确返回两段实现结果。

传统意义上的“多重继承”指一个类同时继承多个父类,容易引入菱形继承二义性;C# 明确禁止类的多重继承,转而采用“单基类 + 多接口”模式组合多种行为契约(例如 `class PaintedRectangle : Shape, IPaintCost` 既继承图形尺寸状态,又实现油漆计价契约)。本站实测 `PaintedRectangle(5, 7)` 面积 `35`、油漆成本 `2450`,且运行期同时满足 `is Shape` 与 `is IPaintCost`。

在本地 csc4 实测单类继承、: base(...) 构造初始化顺序、接口继承链与类+接口多重契约

csharp · 阅读源码
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace CSharpInheritanceLab
{
    internal class BaseDemo
    {
        public string SomeMethod()
        {
            return "base-called";
        }
    }

    internal class DerivedDemo : BaseDemo
    {
        public string AnotherMethod()
        {
            return base.SomeMethod() + "+derived";
        }
    }

    internal class Shape
    {
        protected int width;
        protected int height;

        public void SetWidth(int w) { width = w; }
        public void SetHeight(int h) { height = h; }
    }

    internal class SimpleRectangle : Shape
    {
        public int GetArea()
        {
            return width * height;
        }
    }

    internal class RectBase
    {
        protected double length;
        protected double width;
        public static List<string> InitOrder = new List<string>();

        public RectBase(double l, double w)
        {
            length = l;
            width = w;
            InitOrder.Add("RectBase");
        }

        public double GetArea()
        {
            return length * width;
        }

        public string DisplaySummary()
        {
            return string.Format(
                CultureInfo.InvariantCulture,
                "L={0},W={1},A={2}",
                length, width, GetArea()
            );
        }
    }

    internal class Tabletop : RectBase
    {
        public Tabletop(double l, double w) : base(l, w)
        {
            InitOrder.Add("Tabletop");
        }

        public double GetCost()
        {
            return GetArea() * 70.0;
        }

        public new string DisplaySummary()
        {
            return string.Format(
                CultureInfo.InvariantCulture,
                "{0},Cost={1}",
                base.DisplaySummary(), GetCost()
            );
        }
    }

    internal interface IBaseInterface
    {
        string Method1();
    }

    internal interface IDerivedInterface : IBaseInterface
    {
        string Method2();
    }

    internal class MyInterfaceImpl : IDerivedInterface
    {
        public string Method1()
        {
            return "Method1 implementation";
        }

        public string Method2()
        {
            return "Method2 implementation";
        }
    }

    internal interface IPaintCost
    {
        int GetCost(int area);
    }

    internal class PaintedRectangle : Shape, IPaintCost
    {
        public int GetArea()
        {
            return width * height;
        }

        public int GetCost(int area)
        {
            return area * 70;
        }
    }

    internal class Program
    {
        private static string Esc(string s)
        {
            if (s == null) return "null";
            StringBuilder sb = new StringBuilder("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\\': sb.Append("\\\\"); break;
                    case '"': sb.Append("\\\""); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    default:
                        if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
                        else sb.Append(c);
                        break;
                }
            }
            sb.Append("\"");
            return sb.ToString();
        }

        private static string CaseJson(string name, string summary, string expected, string actual)
        {
            bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
            return string.Format(
                "{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
                Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
            );
        }

        private static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            List<string> cases = new List<string>();

            // Case 1: Base & derived class, protected members & base method call
            DerivedDemo dd = new DerivedDemo();
            SimpleRectangle rect = new SimpleRectangle();
            rect.SetWidth(5);
            rect.SetHeight(7);
            string actual1 = string.Format(
                "call={0},area={1},isShape={2}",
                dd.AnotherMethod(), rect.GetArea(), rect is Shape
            );
            cases.Add(CaseJson(
                "base_and_derived_shape",
                "验证派生类通过 base 调用基类方法、访问 protected 字段以及 IS-A 继承关系",
                "call=base-called+derived,area=35,isShape=True",
                actual1
            ));

            // Case 2: Base class constructor initialization via : base(l, w)
            RectBase.InitOrder.Clear();
            Tabletop t = new Tabletop(4.5, 7.5);
            string actual2 = string.Format(
                "order={0},summary={1}",
                string.Join("->", RectBase.InitOrder.ToArray()),
                t.DisplaySummary()
            );
            cases.Add(CaseJson(
                "base_constructor_initialization",
                "验证派生类构造函数通过 : base(l, w) 先于子类体初始化基类并复用 base.DisplaySummary",
                "order=RectBase->Tabletop,summary=L=4.5,W=7.5,A=33.75,Cost=2362.5",
                actual2
            ));

            // Case 3: Interface inheritance
            MyInterfaceImpl impl = new MyInterfaceImpl();
            IBaseInterface asBase = impl;
            string actual3 = string.Format("{0}|{1}", asBase.Method1(), impl.Method2());
            cases.Add(CaseJson(
                "interface_inheritance",
                "验证派生接口继承基接口成员且实现类必须同时实现 Method1 与 Method2",
                "Method1 implementation|Method2 implementation",
                actual3
            ));

            // Case 4: Multiple inheritance simulated via single class + interface
            PaintedRectangle pr = new PaintedRectangle();
            pr.SetWidth(5);
            pr.SetHeight(7);
            int area = pr.GetArea();
            int cost = pr.GetCost(area);
            string actual4 = string.Format(
                "area={0},cost={1},isShape={2},isPaint={3}",
                area, cost, pr is Shape, pr is IPaintCost
            );
            cases.Add(CaseJson(
                "multiple_inheritance_via_interface",
                "验证 C# 通过单类继承结合接口实现(Shape + IPaintCost)完成多重契约组合",
                "area=35,cost=2450,isShape=True,isPaint=True",
                actual4
            ));

            Console.WriteLine(string.Format(
                "{{\"version\":{0},\"cases\":[{1}]}}",
                Esc("CLR " + Environment.Version.ToString()),
                string.Join(",", cases.ToArray())
            ));
        }
    }
}
预期结果 · 待实际运行核验
  • 确认 Shape/Rectangle 继承与 base 调用、Tabletop 构造顺序与成本 2362.5、IDerivedInterface 接口继承实现以及 PaintedRectangle 组合 Shape+IPaintCost 四组实验全部通过。
在本地 csc4 实测单类继承、: base(...) 构造初始化顺序、接口继承链与类+接口多重契约

所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

当前源码 SHA256:7bdab4393537436d8d3bdf8a577b91b832189d3ab84d310f58f582794633ffbc

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载C# 继承实验

所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

ZIP SHA256:962cc556433f31b652c9d2bf3a59fa268ff99529a5182a5b1de52b735b414394

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 C# 中创建派生类实例时,如果基类没有无参构造函数,派生类构造函数必须如何编写?

展开参考解答

派生类构造函数必须在方法头后使用 `: base(参数列表)` 显式调用基类的某个有参构造函数,否则编译器会因找不到基类无参构造函数而报错。

规范与官方依据