【问题标题】:C# - Rewrite If-Else statement with similar code to ternary conditionC# - 用与三元条件类似的代码重写 If-Else 语句
【发布时间】:2021-05-27 16:41:00
【问题描述】:

我想优化以下代码。下面怎么改写

if (cmd.InvoiceRun.BlancoInvoice)
{
    commands.Add(new GenerateBlancoInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc));
}
else
{
    commands.Add(new GenerateInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc));
}

到 if/else 语句到三元语句?

我试过了

cmd.InvoiceRun.BlancoInvoice 
    ? commands.Add(new GenerateInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc))
    : commands.Add(new GenerateBlancoInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc));

但这不被接受,因为 Only assignment, call, increment, decrement, await expression, and new object expressions can be used as a statement.

我希望这是可能的,我需要在三元运算符之前使用 commands.Add 吗?

【问题讨论】:

  • 为什么要将一个非常好的 if/else 重写为三元运算符?
  • 使用三元运算符创建对象并使用单个命令。添加调用。但正如@Sweeper 所说 - 这似乎是一个毫无意义的“优化” - 代码很清楚,编译器可能无论如何都会优化它。
  • 两个类实现的通用基类或接口是什么?
  • @Sweeper 我喜欢三元语句的紧凑性(3 行而不是 6 行)。事实上,这不是一个主要的优化,我只是好奇它是否可能:)
  • @TimSchmelter 两个命令都继承自同一个基类InvoiceCommand

标签: c# .net conditional-statements


【解决方案1】:

我不知道这是否有效

commands.Add(cmd.InvoiceRun.BlancoInvoice 
    ? new GenerateBlancoInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc)
    : new GenerateInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc));

【讨论】:

    【解决方案2】:

    是的,这在 c# 中是不可能的。您需要移动命令。在三元运算符之前添加

    commands.Add(cmd.InvoiceRun.BlancoInvoice 
        ? new GenerateBlancoInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc)
        : new GenerateInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc));
    
    

    在这种情况下,我更喜欢 if-else 语句,因为它更具可读性。

    【讨论】:

      【解决方案3】:

      您不能直接使用conditional operator ? 进行赋值,您可以将它用于返回某些内容的代码。所以你可以用它来确定要添加什么类型的命令:

      InvoiceCommand command = cmd.InvoiceRun.BlancoInvoice 
          ? new GenerateBlancoInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc)
          : new GenerateInvoiceCommand(invoice, cmd.Owner, cmd.CreatedAtUtc);
      commands.Add(command);
      

      【讨论】:

      • 其实可以,但是你必须投一个或另一个,然后它看起来很难看。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2021-09-15
      • 2021-09-10
      • 2019-12-12
      • 2015-03-22
      • 1970-01-01
      • 2017-11-19
      相关资源
      最近更新 更多