虚方法和 override
Coddy 面向 C++ 开发者的 C# 课程的第 38 课,共 48 课。
C++ 和 C# 都使用虚分派,但在 C++ 中,将派生对象赋值给基类值时,值复制可能会造成对象切片。C# 的类引用可以避免这种切片情况。C# 要求使用 override,而不仅仅是签名匹配;使用 new 隐藏成员则是另一回事。
虚成员可以在派生类中重写。override 可以保留通过基类引用进行的多态分派;使用 new 隐藏成员则不同。派生类构造函数可以调用 base 来初始化共享状态。只有当子类型遵守基类约定时,才使用继承。
C++ 参考
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Plan { protected: int unit; public: explicit Plan(int n):unit(n) {} virtual int total(int n) const { return unit*n; } virtual ~Plan()=default; };
class DiscountPlan: public Plan { public: explicit DiscountPlan(int n):Plan(n) {} int total(int n) const override { return Plan::total(n)*9/10; } };
int main() {
DiscountPlan concrete(10); Plan& plan=concrete; cout << plan.total(2) << "\n";
}
C# 支持性声明
class Message { public virtual string Speak() { return "hello"; } }
class LoudMessage : Message { public override string Speak() { return base.Speak().ToUpperInvariant(); } }Main 中的 C# 语句
Message message = new LoudMessage();
Console.WriteLine(message.Speak());这些是用于教学的精简片段。挑战文件包含完整的可执行封装;上面的代码片段展示了相关声明和语句。
参考输出:
18C# 输出:
HELLO挑战
简单完成 Plan.Total 和 DiscountPlan.Total。基础价格为 unit * count。DiscountPlan 返回基础整数总额的 90%,并向下取整。非负输入可确保乘积较小。驱动程序通过 Plan 引用调用,以要求进行虚方法分派。
编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述的行,调用 Exercise.Solve,验证输入未被修改,并在结果末尾输出一个换行符。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。
锁定的启动程序还会独立测试导出的辅助函数或类 API,而不只是测试 Solve 包装函数。
亲手试试
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var a2 = input[2] == "true"; string before2=Snapshot(a2);
Plan p1 = new DiscountPlan(10); Plan p2 = new Plan(10); if (p1.Total(3) != 27 || p2.Total(3) != 30) throw new Exception("Virtual API");
var result = Exercise.Solve(a0,a1,a2);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器