Nạp chồng toán tử: định nghĩa hành vi toán tử cho custom type.
Ví dụ: Box + Box
using System;
namespace Demo
{
class Box
{
private double length, breadth, height;
public double GetVolume() => length * breadth * height;
public void SetLength(double len) { length = len; }
public void SetBreadth(double bre) { breadth = bre; }
public void SetHeight(double hei) { height = hei; }
// Nạp chồng +
public static Box operator +(Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
}
class Tester
{
static void Main(string[] args)
{
Box box1 = new Box();
box1.SetLength(6); box1.SetBreadth(7); box1.SetHeight(5);
Box box2 = new Box();
box2.SetLength(12); box2.SetBreadth(13); box2.SetHeight(10);
Console.WriteLine("Thể tích Box1: {0}", box1.GetVolume()); // 210
Console.WriteLine("Thể tích Box2: {0}", box2.GetVolume()); // 1560
Box box3 = box1 + box2; // Sử dụng operator+
Console.WriteLine("Thể tích Box3: {0}", box3.GetVolume()); // 5400
Console.ReadKey();
}
}
}
Kết quả
Thể tích Box1: 210 Thể tích Box2: 1560 Thể tích Box3: 5400
Quy tắc nạp chồng
public staticreturn type- Ít nhất một operand là containing type
- Không nạp chồng được:
=,.,?:,->,new,typeof,is,as,sizeof - Cặp so sánh: nạp chồng
==phải nạp chồng!=,<với>,<=với>= - True/false operator cho kiểu có thể dùng trong if