基于接口的分派
Coddy 面向 Go 开发者的 C# 课程的第 41 课,共 48 课。
Go 接口通过隐式方式实现;C# 类会显式声明接口。两者都会根据实际传入的值进行分派。Go 中指针接收者和数值接收者的方法集会影响接口满足情况,而 C# 类实现接口时没有这种接收者区别。
基于接口的函数可以接受实现同一契约的不同类型。直接调用接口成员,而不是根据具体类型进行切换。这样,调用方就可以注入测试实现或新的通知器,而无需更改路由器。本课不会联系任何服务。
Go 参考
package main
import ("fmt")
type Notifier interface{Send(string)string}
type Email struct{}
func(Email)Send(message string)string{return "email:"+message}
func main() {
var notifier Notifier=Email{};fmt.Println(notifier.Send("ok"))
}C# 支持性声明
interface IMeasure { int Measure(string value); }
class TextLength : IMeasure { public int Measure(string value) { return value.Length; } }C# Main 中的语句
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; } }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器