Menu
CoddyTech

基于接口的分派

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

在 Rust 中,你可以选择使用泛型约束(例如 impl Notifier)进行静态分发,也可以通过 &dyn Notifier 进行动态分发。C# 中,接口类型的参数会在运行时进行分发,无需 dyn 标记;类只需在自己的声明中列出接口即可实现接口,而不必使用单独的 impl 块。路由器必须调用传入的接口对象,而不是自行创建某个特定的通知器。

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

Rust 参考

trait Notifier {
    fn send(&self, message: &str) -> String;
}

struct EmailNotifier;

impl Notifier for EmailNotifier {
    fn send(&self, message: &str) -> String {
        format!("email:{}", message)
    }
}

fn main() {
    let notifier: &dyn Notifier = &EmailNotifier;
    println!("{}", 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自我测试

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

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

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