这是关于绑定返回不同类型的单子的a similar one I asked个后续问题.在得到一个明确的答案后,我意识到我没有问完整的问题.马克·西曼(回答者)建议我把这个问题作为一个新问题来问,而不是修改这个问题(这个问题本身就存在,所以值得留下来).
为了简单起见,我正在介绍一个不太现实的用例(例如角色判断可以以不同的方式完成,等等),但我尽量不混淆这个问题,所以请耐心听我说.
假设我想写一个接受int
的方法,并且需要...
- 判断所使用的授权人是否处于发出请求的适当角色
- 判断数据库中与客户对应的Id
- 判断客户是否处于活动状态
如果我们完成了所有这些任务,我们将返回客户,否则我们将返回错误消息.所有方法均为async
.
我有以下(简化的)方法...
async static Task<Either<string, int>> CheckUser(int id) {
// Check the authed user is in the right role, etc. For simplicity, we'll just branch on the id
// Simulate some async work
await Task.Delay(0);
if (id < 0) {
return "Invalid";
}
return id;
}
async static Task<Option<Customer>> Exists(int id) {
// Check the customer id refers to a real customer. Simulate some async work
await Task.Delay(0);
return id < 10 ? None : new Customer(id, "Jim Spriggs");
}
async static Task<Either<string, Customer>> IsActive(Customer c) {
// Simulate some async work
await Task.Delay(0);
if (c.Id % 2 == 0) {
return "Inactive";
}
return c;
}
record Customer(int Id, string Name);
我想把这些结合在一起,如下所示(实际上,我要做的不仅仅是将结果写入控制台,但你明白了)...
await CheckUser(31)
.Bind(async id => (await Exists(id)).ToEither("No such customer"))
.Bind(IsActive)
.Match(n => Console.WriteLine($"Success: {n}"), ex => Console.WriteLine($"Ex: {ex}"));
然而,我在第二行的id
参数到Exists
参数上得到了一个编译器错误..."CS1503 Argument 1: cannot convert from 'LanguageExt.Either<string, int>' to 'int'"
我试过有await/async
个关键字和没有await/async
个关键字,但还是无法编译.我不确定是否需要将它们添加到lambda中.
有人能解释我是怎么做到的吗?谢谢