请考虑以下2种方法。主体是相同的-唯一的区别是方法的第二个参数(矩形与矩形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());
}
答案 0 :(得分:3)
这是我认为可以减少代码重复的最佳方法:
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));
}
答案 1 :(得分:2)
您可以尝试使用RectangleF.Implicit(Rectangle to RectangleF) Operator
,让Rectangle
到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);
}
答案 2 :(得分:1)
您可以定义一个采用通用参数作为IEnumerable的通用方法。
然后我们将is作为对象进行转换,并获取其类型为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);
}