运算符在C#中重载

Rag*_*v55 10 c# operator-overloading

class Point
{
    private int m_PointX;
    private int m_PointY;

    public Point(int x, int y)
    {
        m_PointX = x;
        m_PointY = y;
    }

    public static Point operator+(Point point1, Point point2)
    {
        Point P = new Point();
        P.X = point1.X + point2.X;
        P.Y = point1.Y + point2.Y;

        return P;
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

Point P1 = new Point(10,20);
Point P2 = new Point(30,40)
P1+P2; // operator overloading
Run Code Online (Sandbox Code Playgroud)
  1. 是否有必要始终将运算符重载函数声明为静态?这背后的原因是什么?
  2. 如果我想重载+接受像2 + P2这样的表达式,怎么做?

Dan*_*ite 10

  1. 是.因为您不是始终与运营商一起处理实例.
  2. 只需将类型更改为您想要的类型.

这是#2的一个例子

public static Point operator+(int value, Point point2)
{
 // logic here.
}
Run Code Online (Sandbox Code Playgroud)

如果你想P2 + 2工作,你将不得不使用参数的另一种方式.

有关更多信息,请参见http://msdn.microsoft.com/en-us/library/8edha89s.aspx.