c# - 如何去除多个 if-else 或重复的三元运算?

标签 c# .net-core

我想使用 DRY 原则制作以下功能。

private void DetermineLeftAndRightPoint(Coordinate coordinate1, Coordinate coordinate2)
{
    // If false, then parallel to Y axis
    if (IsParallelToXAxis == true)
    {
        LeftPoint = coordinate1.X < coordinate2.X ? coordinate1 : coordinate2;
        RightPoint = coordinate1.X < coordinate2.X ? coordinate2 : coordinate1;
        return;
    }

    LeftPoint = coordinate1.Y < coordinate2.Y ? coordinate1 : coordinate2;
    RightPoint = coordinate1.Y < coordinate2.Y ? coordinate2 : coordinate1;
}

我尝试创建另一个带有“out”参数的函数来确定线段平行于 X 或 Y 时的左点和右点,但随后我不得不再次使用 if-else 选择 X/Y 参数。有没有更好的方法来编写函数?

最佳答案

我建议提取一个,而不是实现out 参数、if else 和三元运算符,我们可以在其中放置所有相应的逻辑:

public enum ParallelToAxis {
  None,
  X,
  Y 
}

public class Segment {
  public Segment(Coordinate left, Coordinate right)
    : this(left, right, ParallelToXAxis.None); 

  public Segment(Coordinate left, Coordinate right, ParallelToAxis kind) {
    // Should we swap left and right?
    if (kind == ParallelToAxis.X && left.X > right.X ||
        kind == ParallelToAxis.Y && left.Y > right.Y) {
      Left = right;
      Right = left; 
    }
    else { 
      Left = left;
      Right = right;
    }
  }

  public Coordinate Left {get;}
  public Coordinate Right {get;} 
  ...
  //TODO: Implement Equals, GetHashCode, ToString() etc.  
}

那么你就可以简单的写成

private void DetermineLeftAndRightPoint(Coordinate coordinate1, Coordinate coordinate2)
{
    Segment seg = new Segment(
      coordinate1, 
      coordinate2, 
      IsParallelToXAxis ? ParallelToAxis.X | ParallelToAxis.None);

    LeftPoint = seg.Left;
    RightPoint = seg.Right;
}

您可以更进一步,摆脱单个 Segment 属性的 LeftPointRightPoint

关于c# - 如何去除多个 if-else 或重复的三元运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57354811/

相关文章:

c# - 如何从 SourceForge 获取 MD5 码

c# - 自定义 MSBuild 任务 : how to flush logging in VS2012 output window while task is still running?

c# - 更改字符串以将 "A"、 "An"、 "The"移动到 c# 中字符串末尾的最佳方法

c# - dotnet pack项目引用

c# - 创建RSA公钥和私钥

iis - HTTP 错误 500.19 - Windows Server 2012 R2 中的内部服务器错误

javascript - 比较多个动态生成的下拉列表的选定值

c# - List<T> 上的通用排序

.net - 在 Mac 和 Windows 上打开相同的 .NET Core 解决方案

c# - 找不到 Microsoft.AspNetCore.Antiforgery