为了简单起见,我正在介绍一个不太现实的用例(例如角色判断可以以不同的方式完成,等等),但我尽量不混淆这个问题,所以请耐心听我说.

假设我想写一个接受int的方法,并且需要...

  1. 判断所使用的授权人是否处于发出请求的适当角色
  2. 判断数据库中与客户对应的Id
  3. 判断客户是否处于活动状态

如果我们完成了所有这些任务,我们将返回客户,否则我们将返回错误消息.

如果我在第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行?如果是后者,我该如何修复代码?

谢谢

推荐答案

使用ToEither:

[Fact]
public void Answer()
{
    var actual = CheckUser(36)
        .Bind(i => Exists(i).ToEither("Inactive"))
        .Bind(IsActive)
        .Match(n => $"Success: {n}", ex => $"Ex: {ex}");
    Assert.Equal("Ex: Inactive", actual);
}

上述测试通过.

Csharp相关问答推荐

我可以将Expressc操作设置为在另一个Expressc操作完成后自动发生吗?

我应该将新的httpReportMessage()包装在using声明中吗?

Microsoft.AspNetCore.Mvc. Controller Base.用户:属性或索引器Controller Base.用户无法分配给--它是只读的

FromServices不使用WebAppliationFactory程序>

CS0103 dlibdotnet和www.example.com facerect不在上下文中

数组被内部函数租用时,如何将数组返回给ArrayPool?

迭代C#List并在数据库中 for each 元素执行SELECT语句—更有效的方式?

Unity中的刚体2D运动

可为空的泛型属性

Azure DEVOPS找不到定制的Nuget包

C#EF Core WHERE IN LINQ FROM LIST WITH.CONTAINS不返回任何内容

用于管理System.Text.Json中的多态反序列化的自定义TypeInfoResolver

关于扩展文件类C#的矛盾

在implementationFactory中避免循环依赖

如何实现有条件的自定义Json转换器隐藏属性

如何在单击按钮后多次异步更新标签

如何在C#控制台应用程序中获取用户输入并将其作为订单项目进行处理?

ASP.NET核心8:app.UseStaticFiles()管道执行顺序

当要删除的子模型没有父模型的1:多属性时,如何告诉实体框架设置1:1 FK条目?

Unity 3D-意外轴捕捉和未知力对脉冲react 行为的影响