基于接口的分派
Coddy 面向 Python 开发者的 C# 课程的第 41 课,共 48 课。
Python 调用方通常通过鸭子类型依赖方法名。C# 使用显式的 INotifier 契约,并通过它进行分派。路由器必须使用提供的对象,而不是构造特定的通知器,这样新的实现才能保持可替换性。
基于接口的函数可以接受同一契约的不同实现。调用接口成员,而不是根据具体类型进行切换。这种设计允许调用方注入测试实现或新的通知器,而无需更改路由器。本课不会联系任何服务。
Python 参考
class EmailNotifier:
def send(self, message):
return "email:" + message
notifier = EmailNotifier()
print(notifier.send("ok"))C# 支持性声明
interface INotifier { string Send(string message); }
class EmailNotifier : INotifier { public string Send(string message) { return "email:"+message; } }Main 中的 C# 语句
INotifier notifier = new EmailNotifier();
Console.WriteLine(notifier.Send("ok"));这些是用于教学的精简示例。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。
参考输出:
email:okC# 输出:
email:ok挑战
简单实现 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; } }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器