Given the following code, I try to implement the
p开发者_如何学Goublic static Point operator +(int x, Point p1)
by reusing the
public static Point operator +(Point p1, int x)
but it doesn't work. Is it true that we cannot do this in C#?
thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point() { }
public Point(int x, int y)
{
X = x;
Y = y;
}
public override string ToString()
{
return string.Format("x: {0}, y: {1}", X, Y);
}
public static Point operator+(Point p1, Point p2)
{
return new Point(p1.X + p2.X, p1.Y + p2.Y);
}
public static Point operator +(Point p1, int x)
{
return new Point(p1.X+x, p1.Y+x);
}
public static Point operator +(int x, Point p1)
{
return Point.operator+(p1, x); // **doesn't compile**
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(1, 2);
Point p2 = new Point { X = 3, Y = 4 };
Console.WriteLine("p1: {0}", p2);
Console.WriteLine("p2: {0}", p1);
Console.WriteLine("p1+p2: {0}", p1+p2);
Console.WriteLine("p1+10: {0}", p1 + 10);
Console.WriteLine("p1+10: {0}", 10 + p1);
Console.ReadLine();
}
}
}
// updated for the compiler errors //
Error 1 Invalid expression term 'operator' C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 26 ConsoleApplication2
Error 2 Identifier expected; 'operator' is a keyword C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 26 ConsoleApplication2
Error 3 Invalid expression term ',' C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 38 ConsoleApplication2
Error 4 ) expected C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 38 ConsoleApplication2
Error 5 ; expected C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 40 ConsoleApplication2
Error 6 Invalid expression term ')' C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 41 ConsoleApplication2
Error 7 ; expected C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 41 ConsoleApplication2
You can certainly reuse the operator, just like this:
public static Point operator +(int x, Point p1)
{
return p1 + x;
}
There's no syntax to explicitly call an operator as if it were a method though.
try
public static Point operator +(int x, Point p) { return p + x; }
精彩评论