重载+运算符以添加两个数组

Ant*_*zer 7 c# operator-overloading

这个C#代码有什么问题?我试图重载+运算符以添加两个数组,但收到如下错误消息:

二元运算符的参数之一必须是包含类型.

class Program
{
  public static void Main(string[] args)
  {
      const int n = 5;

      int[] a = new int[n] { 1, 2, 3, 4, 5 };
      int[] b = new int[n] { 5, 4, 3, 2, 1 };
      int[] c = new int[n];

      // c = Add(a, b);
      c = a + b;

      for (int i = 0; i < c.Length; i++)
      {
        Console.Write("{0} ", c[i]);
      }

      Console.WriteLine();
  }

  public static int[] operator+(int[] x, int[] y)
  // public static int[] Add(int[] x, int[] y)
  {
      int[] z = new int[x.Length];

      for (int i = 0; i < x.Length; i++)
      {
        z[i] = x[i] + y[i];
      }

      return (z);
  }
}
Run Code Online (Sandbox Code Playgroud)

Bry*_*ard 17

必须在"相关"类的主体内声明操作符.例如:

public class Foo
{
    int X;

    // Legal
    public static int operator+(int x, Foo y);

    // This is not
    public static int operator+(int x, int y);
}
Run Code Online (Sandbox Code Playgroud)

由于您无法访问数组的实现,因此最好的办法是将数组包装在自己的实现中,以便提供额外的操作(这是使运算符+工作的唯一方法.

另一方面,您可以定义一个扩展方法,如:

public static class ArrayHelper
{
    public static int[] Add(this int[] x, int[] y) { ... }
}
Run Code Online (Sandbox Code Playgroud)

仍然会导致自然调用(x.Add(y)),同时避免在自己的类中包装数组.