我想使用干原理来制作以下功能。
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
和Tirnary Operators我建议提取A class 我们可以放置所有相应的逻辑:
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;
}
您可以进一步摆脱LeftPoint
和RightPoint
的单个Segment
属性