PointF 的重载 + 运算符

Overload + Operator for PointF

我是 c# 和 windows 编程的新手。我知道在 C# 中,有一个很棒的功能叫做运算符重载。我想在我的代码中应用这种技术。在下面的代码中,我想定义二进制 + 运算符,以便我可以连接两个 PointF 对象。

在行 pointList.Add(point + center) 中,我得到一个错误:

Error 1 Operator '+' cannot be applied to operands of type 'System.Drawing.PointF' and 'System.Drawing.PointF'

我不确定为什么会出现此错误,因为我已经为 PointF 重载了运算符 +。

 private static PointF operator+ (PointF point_left, PointF point_right) {
            return new PointF(point_left.X + point_right.X, point_left.Y + point_right.Y);
        }

        private void Form1_Paint(object sender, PaintEventArgs e) {
            List<PointF> pointList = new List<PointF>();
            PointF center = new PointF(50, 50);
            int radius = 50;
            for (int i = 0; i < 5; ++i) {
                double degree = (2.0 * Math.PI * i) / 5.0;
                PointF point = new PointF((float)(radius * Math.Cos(degree)), (float)(radius * Math.Sin(degree)));
                pointList.Add(point + center);
            }
            Brush brush = new LinearGradientBrush(new Point(20, 20), new Point(50, 50), 
                Color.Red, Color.Blue);
            e.Graphics.FillPolygon(brush, pointList.ToArray());
        }

编辑:在我重新编译代码后,我得到了一个不同的错误:

one of the parameters of a binary operator must be the containing type

我真的很想为 PointF 重载 + 运算符。有什么解决办法吗?在 C++ 中,可以通过使用全局函数为不同的 class 重载运算符。如何为 c# 实现?

根据 C# operator overloading rules,您必须将运算符重载声明为 public static。这可能是您在这里遇到问题的原因,但如果没有错误的话我会感到惊讶。

您不能扩展内置结构和类来添加运算符。

或者,您可以创建一个扩展方法来完成工作:

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

用法是:

 var p1 = new PointF(1, 1);
 var p2 = new PointF(2, 2);
 reult =p1.Add(p2);