Menu
CoddyTech

基于接口的分派

Coddy 面向 Dart 开发者的 C# 课程的第 41 课,共 48 课。

Dart 接口分派和 C# 接口分派都会调用调用方提供的实现。Dart 可以实现任何类的接口;C# 使用具名接口声明。不要在路由器中将注入的通知器替换成具体的 Email。

基于接口的函数可以接受实现同一契约的不同实现。调用接口成员,而不是根据具体类型进行切换。这样,调用方就能注入测试实现或新的通知器,而无需更改路由器。本课不会联系任何服务。

Dart 参考

abstract class Notifier { String send(String message); }
class Email implements Notifier { String send(String message)=>"email:$message"; }
void main() {
Notifier notifier = Email(); print(notifier.send("ok"));
}

C# 支持声明

interface IMeasure { int Measure(string value); }
class TextLength : IMeasure { public int Measure(string value) { return value.Length; } }

Main 中的 C# 语句

IMeasure measure = new TextLength();
Console.WriteLine(measure.Measure("word"));

这些是用于教学的重点摘录。挑战文件包含完整的可执行封装;上面的代码片段展示了相关声明和语句。

参考输出:

email:ok

C# 输出:

4
challenge icon

挑战

简单

实现 EmailNotifier.Send、SmsNotifier.Send 和 Router.Deliver。channel 可以是 email 或 sms。每个通知器都会在消息前加上对应的渠道名称和冒号。Router 会把调用委托给调用方提供的任意 INotifier。这些只是文本格式化模型,并不是真实的网络消息传递。

编辑未锁定的 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 = input[0]; string before0=Snapshot(a0);
var a1 = input[1]; string before1=Snapshot(a1);
if (new EmailNotifier().Send("") != "email:" || new SmsNotifier().Send("x") != "sms:x" || Router.Deliver(new ProbeNotifier(),"x") != "custom:x") throw new Exception("Notifier 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 ProbeNotifier : INotifier { public string Send(string message) { return "custom:"+message; } }
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Dart 开发者的 C#中的所有课

自己练习: C# 在线编译器