如何用不同的参数实现一个方法.c#



伙计们,请告诉我这个逻辑是如何被拉到一个单独的方法中,因为有一个重复的代码,但比较操作符略有不同。c# .

public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2)
{
if (r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom)
return 0;
if (r1.Left <= r2.Left && r1.Right >= r2.Right && r1.Top <= r2.Top && r1.Bottom >= r2.Bottom)
return 1;
return -1;
}

您可以提取一个更简单的方法

public static bool IsLeftRectangleCompletelyWithinRightRectangle(Rectangle r1, Rectangle r2)
{
return (r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom)
}

然后像

一样使用
public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2)
{
if (IsLeftRectangleCompletelyWithinRightRectangle(r1, r2))
return 0;
if (IsLeftRectangleCompletelyWithinRightRectangle(r2, r1))
return 1;
return -1;
}

我想你可以用

public static bool IsR1InsideR2(Rectangle r1, Rectangle r2)
{
return r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom);
}

然后调用它两次,为第二次调用交换rects:

var a = ...
var b = ...
if(IsR1InsindeR2(a,b))
return 0; //or whatever you did with the 0
if(IsR1InsindeR2(b,a))
return 1; //or whatever
return -1; //or whatever

使其成为扩展或实例方法可能会提高可读性:

public static bool Inside(this Rectangle r1, Rectangle r2)
{
return r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom);
}
//usage
a.Inside(b);

如果这些是System.Drawing.Rectangle,请检查它们的Contains方法。

最新更新