C#操作符的重载
c#要求所有的运算符重载都声明为public 和static,这表示他们与他们的类或结构相关联,而不与实例相关联。操作符的重载使用operator关键字,C#不允许重载=操作符。
下面是一个重载+操作符的列子,
代码
static void Main(string[] args)
{
Square a = new Square(3, 3);
Square b = new Square(5, 5);
Square c = new Square();
c = a + b;
Console.WriteLine(c.ToString());
Console.ReadKey();
}
public class Square
{
public Square() { }
public Square(int w,int h)
{
this.w = w;
this.h = h;
}
public Square(int area)
{
this.area=area;
}
public int w { get; set; }
public int h { get; set; }
public int area{get;set;}
public static Square operator +(Square a,Square b)
{
return new Square(a.w*a.h+b.w*b.h);
}
public override string ToString()
{
return this.area.ToString();
}
}
{
Square a = new Square(3, 3);
Square b = new Square(5, 5);
Square c = new Square();
c = a + b;
Console.WriteLine(c.ToString());
Console.ReadKey();
}
public class Square
{
public Square() { }
public Square(int w,int h)
{
this.w = w;
this.h = h;
}
public Square(int area)
{
this.area=area;
}
public int w { get; set; }
public int h { get; set; }
public int area{get;set;}
public static Square operator +(Square a,Square b)
{
return new Square(a.w*a.h+b.w*b.h);
}
public override string ToString()
{
return this.area.ToString();
}
}