Overloading the + operator to add two arrays

后端 未结 5 1741
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 18:53

What\'s wrong with this C# code? I tried to overload the + operator to add two arrays, but got an error message as follows:

One of the parameters of a binary operato

5条回答
  •  醉话见心
    2020-12-03 19:27

    You can use something like this:

    class Program {
      static void Main(string[] args) {
        const int n = 5;
    
        var a = new int[n] { 1, 2, 3, 4, 5 }.WithOperators();
        var b = new int[n] { 5, 4, 3, 2, 1 };
    
        int[] c = a + b;
    
        for (int i = 0; i < c.Length; i++) {
          Console.Write("{0} ", c[i]);
        }
    
        Console.WriteLine();
      }
    }
    
    public static class Int32ArrayExtensions {
      public static Int32ArrayWithOperators WithOperators(this int[] self) {
        return self;
      }
    }
    
    public class Int32ArrayWithOperators {
      int[] _array;
    
      public Int32ArrayWithOperators(int[] array) {
        if (array == null) throw new ArgumentNullException("array");
        _array = array; 
      }
    
      public static implicit operator Int32ArrayWithOperators(int[] array) {
        return new Int32ArrayWithOperators(array); 
      }
      public static implicit operator int[](Int32ArrayWithOperators wrapper) {
        return wrapper._array;
      }
    
      public static Int32ArrayWithOperators operator +(Int32ArrayWithOperators left, Int32ArrayWithOperators right) {
        var x = left._array;
        var y = right._array;
        return x.Zip(y, (a, b) => a + b).ToArray();
      }
    }
    

    Based on a related post that I wrote.

提交回复
热议问题