为了简单起见,我正在介绍一个不太现实的用例(例如角色判断可以以不同的方式完成,等等),但我尽量不混淆这个问题,所以请耐心听我说.
假设我想写一个接受int
的方法,并且需要...
- 判断所使用的授权人是否处于发出请求的适当角色
- 判断数据库中与客户对应的Id
- 判断客户是否处于活动状态
如果我们完成了所有这些任务,我们将返回客户,否则我们将返回错误消息.
如果我在第2步中使用Either
返回方法,我可以这样做...
static Either<string, int> CheckUser(int n) {
// Check the authed user is in the right role, etc
// For simplicity, we'll decide based on the Id
if (n < 0) {
return "Not authorised to access customer data";
}
return n;
}
static Either<string, Customer> Exists(int n) =>
// This would check the database
n < 10 ? "Unknown customer" : new Customer(n, "Jim Spriggs");
static Either<string, Customer> IsActive(Customer c) {
// This would check the customer, we just use a simple check on the Id for simplicity
if (c.Id % 2 == 0) {
return "Inactive";
}
return c;
}
record Customer(int Id, string Name);
然后我可以如下将其绑定在一起...
CheckUser(36)
.Bind(Exists)
.Bind(IsActive)
.Match(n => Console.WriteLine($"Success: {n}"), ex => Console.WriteLine($"Ex: {ex}"));
这是可行的,但我忍不住觉得Exists
方法应该返回Option<Customer>
而不是Either<string, Customer>
,例如(为了清晰起见再次简化)...
static Option<Customer> Exists(int n) =>
n < 10 ? Option<Customer>.None : new Customer(n, "Jim Spriggs");
然而,我正在努力解决如何在其他两种方法之间进行绑定.我想我可以用Map
来转换,但不知道怎么做.
有人能提供建议吗?用Either
行吗,还是用Option
行?如果是后者,我该如何修复代码?
谢谢