重载+运算符将两个数组 [英] Overloading the + operator to add two arrays

查看:100
本文介绍了重载+运算符将两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么不对的C#code?我试图重载+运算符将两个数组,却得到了一个错误信息如下:

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

 类节目
{
  公共静态无效的主要(字串[] args)
  {
      const int的N = 5;      INT []一个=新INT [n]的{1,2,3,4,5};
      INT [] B =新INT [n]的{5,4,3,2,1};
      INT [] C = INT新[N];      // C =添加(A,B);
      C = A + B;      的for(int i = 0; I< c.Length;我++)
      {
        Console.Write({0},C [I]);
      }      Console.WriteLine();
  }  公共静态INT []运算符+(INT []×,INT [] Y)
  //公共静态INT []添加(INT []×,INT [] Y)
  {
      INT [] Z =新INT [x.Length]      的for(int i = 0; I< x.Length;我++)
      {
        Z [i] = X [I] + Y [I]
      }      返回(Z);
  }
}


解决方案

运营商必须是相关类的主体内声明。例如:

 公共类Foo
{
    INT X;    法律//
    公共静态INT运营商+(INT X,富Y);    // 这不是
    公共静态INT运营商+(INT X,int y)对;
}

由于您没有访问阵列的实施,你最好的选择是要么换你的阵列在您自己的实现,这样可以提供额外的操作(这是使运营商+工作的唯一途径。

在另一方面,你可以定义喜欢的扩展方法:

 公共静态类ArrayHelper
{
    公共静态INT []添加(这INT []×,INT [] Y){...}
}

该仍将导致天然电话( x.Add(Y)),同时避免包装阵列在自己的类。

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 operator must be the containing type.

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

解决方案

Operators must be declared inside a "related" class' body. For instance:

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

Since you don't have access to the implementation of arrays, your best bet would be to either wrap your arrays in your own implementation so you can provide additional operations (and this is the only way to make the operator+ work.

On the other hand, you could define an extension method like:

public static class ArrayHelper
{
    public static int[] Add(this int[] x, int[] y) { ... }
}

The will still lead to natural calls (x.Add(y)) while avoiding to wrap arrays in your own class.

这篇关于重载+运算符将两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆