一起添加System.Drawing.Points [重复项]

问题描述 投票:2回答:1

此问题已经在这里有了答案:

我遇到了以下代码,这些代码使用System.Drawing.Size类的构造函数添加两个System.Drawing.Point对象。

// System.Drawing.Point mpWF contains window-based mouse coordinates
// extracted from LParam of WM_MOUSEMOVE message.

// Get screen origin coordinates for WPF window by passing in a null Point.
System.Windows.Point originWpf = _window.PointToScreen(new System.Windows.Point());

// Convert WPF doubles to WinForms ints.
System.Drawing.Point originWF = new System.Drawing.Point(Convert.ToInt32(originWpf.X),
    Convert.ToInt32(originWpf.Y));

// Add WPF window origin to the mousepoint to get screen coordinates.
mpWF = originWF + new Size(mpWF);

[我认为在上一条语句中使用+ new Size(mpWF)是一个hack,因为当我阅读上面的代码时,它使我放慢了速度,因为我不立即了解发生了什么。

我尝试如下解构最后一条语句:

System.Drawing.Point tempWF = (System.Drawing.Point)new Size(mpWF);
mpWF = originWF + tempWF;  // Error: Addition of two Points not allowed.

但是它没有用,因为没有为两个System.Drawing.Point对象定义加法。还有什么其他方法可以对两个Point对象执行加法,比原始代码更直观?

c# wpf winforms system.drawing mousemove
1个回答
4
投票

为此创建Extension Method

public static class ExtensionMethods
{
    public static Point Add(this Point operand1, Point operand2)
    {
        return new Point(operand1.X + operand2.X, operand1.Y + operand2.Y);
    }
}

用法:

 var p1 = new Point(1, 1);
 var p2 = new Point(2, 2);
 var reult =p1.Add(p2);
© www.soinside.com 2019 - 2024. All rights reserved.