基于接口的分派
Coddy 面向 C 开发者的 C# 课程的第 41 课,共 48 课。
在 C 中,要让路由器适用于任意通知器,可以使用指向函数指针结构体的指针,或根据类型标记进行分支;调用方还需要提供用于写入结果的缓冲区。C# 接口引用也能实现相同的替换,并提供经过检查的契约:任何实现该接口的类都可以传入,一个类可以实现多个接口,而且结果是普通的托管字符串。路由器必须调用传入的接口对象,而不能自行创建某个特定的通知器。
基于接口的函数可以接受实现同一契约但彼此无关的对象。调用接口成员,而不是根据具体类型进行分支。采用这种设计,调用方可以注入测试实现或新的通知器,而无需修改路由器。本课不会连接任何服务。
C 参考
#include <stdio.h>
struct Notifier {
void (*send)(const char *message, char *out, size_t size);
};
static void email_send(const char *message, char *out, size_t size) {
snprintf(out, size, "email:%s", message);
}
static void route(const struct Notifier *notifier, const char *message) {
char buffer[64];
notifier->send(message, buffer, sizeof buffer);
printf("%s\n", buffer);
}
int main(void) {
struct Notifier email = { email_send };
route(&email, "ok");
return 0;
}
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:okC# 输出:
4挑战
简单实现 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; } }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器