简体   繁体   中英

C# Program addition operator for Point

I'm using C# XNA and I found when trying to add two points together it won't let me. Is there some way I can add to the Point class to allow this code to run.

Point a = new Point(3,4);
Point b = new Point(6,2);
Point c = a + b; //Should equal new Point(9,6);

You could simply overload the + operator - like this:

class Point
{
    public int X { get; private set; }
    public int Y { get; private set; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public static Point operator +(Point p1, Point p2)
    {
        return new Point(p1.X + p2.X, p1.Y + p2.Y);
    }
}

Now, your code compiles as work as you expect it to:

Point a = new Point(3, 4);
Point b = new Point(6, 2);
Point c = a + b; //Should equal new Point(9,6); - and it is :)

More info on operator overloading can be found on MSDN .

Add to a separate class.

public static void Add(this Point a, Point b){
     a.X += b.X;
     a.Y += b.Y;
}

You can add a Size struct to a Point struct , and easily convert between them by passing a Point in to a Size constructor like this:

c = a + (new Size(b));

Why DOT NET choose to enforce this subtle distinction between intensive and extensive tuples is beyond me.

You could use extension methods as shown below

class Program
{
    static void Main(string[] args)
    {
        Point a = new Point(1, 2);
        Point b = new Point(2, 4);

        Point c=a.AddPoints(b);
    }
}

public static class MyExtensions
{
    public static Point AddPoints(this Point x, Point y)
    {
        return new Point(x.X + y.X, x.Y + y.Y);
    }
}  

Technically, you could use a static method, extension method and maybe even an operator overload, as other answers suggest.

However, .NET has both Point and Size to capture a semantic distinction:

  • Point refers to a point, usually compared to an arbitrary reference point.
  • Size refers to a vector - distance with a direction, or distance X & distance Y.

Adding Point s would be meaningless. For example, if Point s refer to coordinates on a geographic map - what would their mean? "50° latitude" + "60° latitude" = "110° latitude"? That's why .NET wisely chose not to implement an addition operator.

However, adding Point and Size can have reasonable meaning - "50° latitude" + "1° latitude distance" = "51° latitude" is a good answer.

PS. Notice the similarity to the distinction between DateTime and TimeSpan .

TL;DR - One or both of your Point s should actually be a Size - change it at the earliest location possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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