我想使用 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
属性的 LeftPoint
和 RightPoint
关于c# - 如何去除多个 if-else 或重复的三元运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57354811/