简体   繁体   English

C#中的运算符重载

[英]operator Overloading in C#

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;
    }
}

Example:例子:

Point P1 = new Point(10,20);
Point P2 = new Point(30,40)
P1+P2; // operator overloading
  1. Is it necessary to always declare the operator overloading function as static?是否有必要始终将运算符重载函数声明为静态? What is the reason behind this?这背后的原因是什么?
  2. If I want to overload + to accept the expression like 2+P2, how to do this?如果我想重载 + 来接受像 2+P2 这样的表达式,该怎么做?
  1. Yes.是的。 Because you aren't dealing with instances always with the operators.因为您并不总是使用运算符来处理实例。
  2. Just change the types to what you want.只需将类型更改为您想要的类型。

Here is an example for #2这是#2的示例

public static Point operator+(int value, Point point2)
{
 // logic here.
}

You will have to do the other way with the parameters if you want P2 + 2 to work.如果您希望P2 + 2工作,则必须对参数进行另一种方式。

See http://msdn.microsoft.com/en-us/library/8edha89s.aspx for more information.有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/8edha89s.aspx

To answer your questions:回答您的问题:

  1. Yes, you need to define them as static.是的,您需要将它们定义为静态。 They're not instance methods, they can operate on null s as well.它们不是实例方法,它们也可以对null进行操作。
  2. You'll have to define an operator overload where one of the parameters are of type int您必须定义一个运算符重载,其中一个参数是int类型

Both of the previous answers talk about your questions, so I'm not going to intrude on those, but here is an example of using 2+P:前面的两个答案都讨论了您的问题,因此我不会介入这些问题,但这里有一个使用 2+P 的示例:

   public static Point operator+(int yourInt, Point point)
    {
        Point P = new Point();
        P.X = point.X + yourInt;
        P.Y = point.Y + yourInt;

        return P;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM