[英]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.