日期:2014-05-18  浏览次数:20750 次

C#重载运算符没起作用
class Program
  {
  public static int operator +(retangle lh, retangle rh) 
  {
  //return new retangle(lh.width + rh.width, lh.height + rh.height);
  return 1;
  }
  static void Main(string[] args)
  {
  retangle r = new retangle(20, 20);
  retangle l = new retangle(10, 7);
  retangle num = new retangle();
  num = r + l; //**************这个地方总提示类型不能相加,求帮助!*****************
  Console.WriteLine(num.width + "" + num.height);
   
  }
   
  }
  public struct retangle
  {
  public int width;
  public int height;

  public retangle(int w, int h)
  {
  this.width = w;
  this.height = h;
  }
  public retangle();
  }

------解决方案--------------------
重载运算符必须声明在其中一个参数的类里面。
由于你这个两个参数都是retangle所以只能声明在retangle类里面,而不是Program类里面。