使用判别联合(记录)进行领域建模——C# 6 模拟
在 C# 6 中使用标签枚举和小型类建模判别联合,创建工厂方法,并通过带有 default throw 的 switch 处理不同变体。
使用判别联合(记录)进行领域建模——C# 6 模拟 是 CoddyKit 上的免费 C# Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。
C# 6 中的 DU 思路
目标:在 C# 6 中构建一个小型判别联合。
- 用于表示当前分支的标签枚举
- 用于存储数据的小型分支类
- 用于创建有效分支的Factory方法
- 使用开关 + 默认抛出异常处理所有变体
标签与工厂方法
使用标签枚举和工厂方法只构造有效分支;其他分支的字段保持未使用状态。
using System;
public enum PaymentKind { Cash, Card, Wire }
public sealed class Payment
{
public PaymentKind Kind;
// per-case data (only one is meaningful per instance)
public string CardLast4; // for Card
public string Iban; // for Wire
private Payment() { }
// factories keep invariants
public static Payment Cash()
{
Payment p = new Payment();
p.Kind = PaymentKind.Cash;
return p;
}
public static Payment Card(string last4)
{
if (string.IsNullOrEmpty(last4) || last4.Length != 4)
throw new ArgumentException("last4 must be 4 digits", "last4");
Payment p = new Payment();
p.Kind = PaymentKind.Card;
p.CardLast4 = last4;
return p;
}
public static Payment Wire(string iban)
{
if (string.IsNullOrEmpty(iban))
throw new ArgumentException("iban must not be empty", "iban");
Payment p = new Payment();
p.Kind = PaymentKind.Wire;
p.Iban = iban;
return p;
}
}
public class Program
{
public static void Main(string[] args)
{
Payment a = Payment.Cash();
Payment b = Payment.Card("1234");
Payment c = Payment.Wire("TR00BANKIBAN");
Console.WriteLine(a.Kind + ", " + b.Kind + ", " + c.Kind);
}
}
处理变体
围绕标签使用传统开关可以清晰地处理各个分支。默认抛出异常会在测试期间暴露未处理的变体。
using System;
public enum PaymentKind { Cash, Card, Wire }
public sealed class Payment
{
public PaymentKind Kind;
public string CardLast4;
public string Iban;
public static Payment Cash()
{
Payment p = new Payment(); p.Kind = PaymentKind.Cash; return p;
}
public static Payment Card(string last4)
{
if (string.IsNullOrEmpty(last4) || last4.Length != 4) throw new ArgumentException("last4");
Payment p = new Payment(); p.Kind = PaymentKind.Card; p.CardLast4 = last4; return p;
}
public static Payment Wire(string iban)
{
if (string.IsNullOrEmpty(iban)) throw new ArgumentException("iban");
Payment p = new Payment(); p.Kind = PaymentKind.Wire; p.Iban = iban; return p;
}
}
public static class Exhaustive
{
public static Exception Unhandled(object x)
{
return new InvalidOperationException("Unhandled case: " + x);
}
}
public class Program
{
static string Describe(Payment p)
{
switch (p.Kind)
{
case PaymentKind.Cash: return "Cash";
case PaymentKind.Card: return "Card ****" + p.CardLast4;
case PaymentKind.Wire: return "Wire " + p.Iban;
default: throw Exhaustive.Unhandled(p.Kind);
}
}
public static void Main(string[] args)
{
Console.WriteLine(Describe(Payment.Card("9876")));
}
}
Match 辅助方法(类似访问者)
小型Match辅助方法集中封装开关并返回值,使调用位置保持简洁。
using System;
public enum PaymentKind { Cash, Card, Wire }
public sealed class Payment
{
public PaymentKind Kind;
public string CardLast4;
public string Iban;
public static Payment Cash() { Payment p = new Payment(); p.Kind = PaymentKind.Cash; return p; }
public static Payment Card(string last4) { Payment p = new Payment(); p.Kind = PaymentKind.Card; p.CardLast4 = last4; return p; }
public static Payment Wire(string iban) { Payment p = new Payment(); p.Kind = PaymentKind.Wire; p.Iban = iban; return p; }
}
public static class PaymentMatch
{
public static T Match<T>(
Payment p,
Func<T> onCash,
Func<string, T> onCard,
Func<string, T> onWire)
{
switch (p.Kind)
{
case PaymentKind.Cash: return onCash();
case PaymentKind.Card: return onCard(p.CardLast4);
case PaymentKind.Wire: return onWire(p.Iban);
default: throw new InvalidOperationException("Unhandled: " + p.Kind);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Payment p = Payment.Card("1234");
string summary = PaymentMatch.Match(
p,
delegate { return "Cash"; },
delegate(string last4) { return "Card ****" + last4; },
delegate(string iban) { return "Wire " + iban; }
);
Console.WriteLine(summary);
}
}
通过工厂维护不变量
工厂会维护不变量:每个分支只初始化自身有意义的字段;无效输入会被尽早拒绝。
using System;
public enum ResultKind { Ok, Error }
public sealed class Result
{
public ResultKind Kind;
public string Message; // only for Error
public int Value; // only for Ok
private Result() { }
public static Result Ok(int value)
{
Result r = new Result();
r.Kind = ResultKind.Ok;
r.Value = value;
r.Message = null;
return r;
}
public static Result Error(string message)
{
if (string.IsNullOrEmpty(message)) throw new ArgumentException("message");
Result r = new Result();
r.Kind = ResultKind.Error;
r.Message = message;
r.Value = 0;
return r;
}
}
public class Program
{
static string Show(Result r)
{
switch (r.Kind)
{
case ResultKind.Ok: return "OK: " + r.Value;
case ResultKind.Error: return "ERROR: " + r.Message;
default: throw new InvalidOperationException("Unhandled: " + r.Kind);
}
}
public static void Main(string[] args)
{
Console.WriteLine(Show(Result.Ok(5)));
Console.WriteLine(Show(Result.Error("Boom")));
}
}
提示与权衡
提示:
- 优先使用小型、职责明确的分支和工厂。
- 在一个位置处理所有变体(通过开关辅助方法),以保持代码符合 DRY 原则。
- 保留默认抛出异常,以便在测试中暴露遗漏的分支。
权衡:样板代码比现代记录类型更多,但表达清晰且兼容 C# 6。
DU 模拟方法
回顾
回顾:使用标签枚举表示变体,通过工厂构建有效分支,并将处理集中到一个开关中(默认分支抛出异常),从而在运行时确保完备性。
常见问题解答
「使用判别联合(记录)进行领域建模——C# 6 模拟」课时是免费的吗?
是的 — 「使用判别联合(记录)进行领域建模——C# 6 模拟」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。
「使用判别联合(记录)进行领域建模——C# 6 模拟」这节课中我会学到什么?
在 C# 6 中使用标签枚举和小型类建模判别联合,创建工厂方法,并通过带有 default throw 的 switch 处理不同变体。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C# Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「使用判别联合(记录)进行领域建模——C# 6 模拟」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C# Academy 课中编写并运行代码吗?
能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- is 模式、关系模式与逻辑模式(C# 6 模拟)
- switch 表达式与使用 when 的穷尽性检查(C# 6 模拟)
- 使用判别联合(记录)进行领域建模——C# 6 模拟