接口与组合
Coddy 面向 Luau 开发者的 C# 课程的第 36 课,共 48 课。
Luau 类型是结构化的:只要某个表的 apply 字段具有正确的函数类型,它就满足 PricePolicy;在运行时,对表字段的调用采用普通的鸭子类型。C# 接口是名义化的:类必须声明自己实现了 IFormatter,仅有匹配的方法还不够。将实现转换为显式的 C# 类时,仍要保留依赖注入。
接口定义了所需成员的契约,实现类则声明与该接口的关系。组合会存储一个协作者,并将工作委托给它。这样一来,Checkout 就不依赖于某个特定的折扣类。驱动程序会注入自己的策略,因此在 Checkout 中硬编码 VIP 算法无法满足 API。
Luau 参考
type PricePolicy = { apply: (self: PricePolicy, price: number) -> number }
local Checkout = {}
Checkout.__index = Checkout
function Checkout.new(policy: PricePolicy)
return setmetatable({ policy = policy }, Checkout)
end
function Checkout:total(price: number): number
return self.policy:apply(price)
end
print(Checkout.new({ apply = function(_, price) return price end }):total(40))C# 支持性声明
interface IFormatter { string Format(string value); }
class Upper : IFormatter { public string Format(string value) { return value.ToUpperInvariant(); } }
class Display { private IFormatter formatter; public Display(IFormatter formatter) { this.formatter = formatter; } public string Render(string value) { return formatter.Format(value); } }Main 中的 C# 语句
Console.WriteLine(new Display(new Upper()).Render("pen"));这些是针对特定内容的教学片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。
参考输出:
40C# 输出:
PEN挑战
简单在各自的文件中实现 StandardPolicy、VipPolicy 和 Checkout。StandardPolicy 返回 price;VipPolicy 使用整数运算返回 90 percent。价格是非负的 10 的倍数。Checkout 必须委托给注入的 IPricePolicy,包括调用方提供的自定义策略。
编辑未锁定的 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 = input[1] == "true"; string before1=Snapshot(a1);
if (new StandardPolicy().Apply(40) != 40 || new VipPolicy().Apply(100) != 90 || new Checkout(new ProbePolicy()).Total(10) != 17) throw new Exception("Policy API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
class ProbePolicy : IPricePolicy { public int Apply(int price) { return price+7; } }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器