C# -- 我们可以将重载运算符称为 ClassName.operator+(p1, p2) 吗?

本文关键字:p1 operator+ p2 ClassName 我们 运算符 重载 | 更新日期: 2023-09-27 17:57:00

给定以下代码,我尝试实现

public static Point operator +(int x, Point p1)

通过重用

public static Point operator +(Point p1, int x)

但它不起作用。我们真的不能在 C# 中做到这一点吗?

谢谢

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

更新了编译器错误//

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

C# -- 我们可以将重载运算符称为 ClassName.operator+(p1, p2) 吗?

您当然可以重用运算符,就像这样:

public static Point operator +(int x, Point p1)
{
    return p1 + x;
}

但是,没有语法可以显式调用运算符,就好像它是一个方法一样。

试试

 public static Point operator +(int x, Point p) { return p + x; }