[英]How to combine two methods with slightly different signatures?
考虑以下两种方法。 主体是相同的-唯一的区别是方法的第二个参数(矩形与矩形F)。 有没有一种方法可以将这两种方法合并为一种,而不必使参数列表复杂化:
public static void DrawRectangles(this Image thisImage, List<RectangleF> rectangles, Color color) {
using (var g = Graphics.FromImage(thisImage)) {
var brush = new SolidBrush(color);
g.FillRectangles(brush, rectangles.ToArray());
}
}
public static void DrawRectangles(this Image thisImage, List<Rectangle> rectangles, Color color) {
using (var g = Graphics.FromImage(thisImage)) {
var brush = new SolidBrush(color);
g.FillRectangles(brush, rectangles.ToArray());
}
我认为这是减少代码重复的最佳方法:
private static void DrawRectangles<T>(this Image thisImage, List<T> rectangles, Color color, Action<Graphics, Brush, T[]> fill)
{
using (var g = Graphics.FromImage(thisImage))
{
var brush = new SolidBrush(color);
fill(g, brush, rectangles.ToArray());
}
}
public static void DrawRectangles(this Image thisImage, List<RectangleF> rectangles, Color color)
{
thisImage.DrawRectangles(rectangles, color, (g, b, rs) => g.FillRectangles(b, rs));
}
public static void DrawRectangles(this Image thisImage, List<Rectangle> rectangles, Color color)
{
thisImage.DrawRectangles(rectangles, color, (g, b, rs) => g.FillRectangles(b, rs));
}
您可以尝试使用RectangleF.Implicit(Rectangle to RectangleF) Operator
,让Rectangle
to RectangleF
然后将其作为参数传递。
public static void DrawRectangles(this Image thisImage, List<RectangleF> rectangles, Color color)
{
using (var g = Graphics.FromImage(thisImage))
{
var brush = new SolidBrush(color);
g.FillRectangles(brush, rectangles.ToArray());
}
}
public static void DrawRectangles(this Image thisImage, List<Rectangle> rectangles, Color color)
{
var rectangleFs = rectangles.Select(x => (RectangleF) x).ToList();
DrawRectangles(thisImage, rectangleFs, color);
}
您可以定义一个采用通用参数作为IEnumerable的通用方法。
然后,我们将as作为对象进行转换,并获取其类型为Rectangle或RectangleF。 根据该逻辑,然后绘制矩形。
public static void DrawRectangles<T>(this Image thisImage, T rectangles, Color color) where T : IEnumerable
{
using (var g = Graphics.FromImage(thisImage))
{
var brush = new SolidBrush(color);
if (rectangles.Cast<object>().FirstOrDefault().GetType() == typeof(Rectangle))
{
g.FillRectangles(brush, rectangles.Cast<Rectangle>().ToArray());
}
else
{
g.FillRectangles(brush, rectangles.Cast<RectangleF>().ToArray());
}
}
}
public static void Main(string[] args)
{
List<Rectangle> r = new List<Rectangle>();
List<RectangleF> rf = new List<RectangleF>();
r.Add(new Rectangle(10, 10, 10, 10));
rf.Add(new RectangleF(10.4f, 10.4f, 10.4f, 10.4f));
DrawRectangles(new Bitmap(10, 10), rf, Color.Aqua);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.