operator Overloading in C#

后端 未结 3 1523
南笙
南笙 2021-01-04 19:24
class Point
{
    private int m_PointX;
    private int m_PointY;

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

    public         


        
相关标签:
3条回答
  • 2021-01-04 19:25
    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

    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.

    See http://msdn.microsoft.com/en-us/library/8edha89s.aspx for more information.

    0 讨论(0)
  • 2021-01-04 19:39

    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:

       public static Point operator+(int yourInt, Point point)
        {
            Point P = new Point();
            P.X = point.X + yourInt;
            P.Y = point.Y + yourInt;
    
            return P;
        }
    
    0 讨论(0)
  • 2021-01-04 19:46

    To answer your questions:

    1. Yes, you need to define them as static. They're not instance methods, they can operate on nulls as well.
    2. You'll have to define an operator overload where one of the parameters are of type int
    0 讨论(0)
提交回复
热议问题