Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách dùng Operator Overloading (Nạp chồng toán tử) trong C#

Toán tử nạp chồng là hàm với tên đặc biệt: từ khóa operator theo sau bởi ký hiệu toán tử. Tương tự hàm khác, overloaded operator có return type và parameter list.

Bảng toán tử có thể/không thể nạp chồng:

STTToán tử & Mô tả
1+, -, !, ~, ++, --
Unary operators (1 operand), có thể nạp chồng.
2+, -, *, /, %
Binary operators (2 operands), có thể nạp chồng.
3==, !=, <, >, <=, >=
Comparison operators, có thể nạp chồng.
4&&, ||
Conditional logical operators KHÔNG nạp chồng trực tiếp.
5+=, -=, *=, /=, %=
Assignment operators KHÔNG nạp chồng.
6=, ., ?:, ->, new, is, sizeof, typeof
Các toán tử này KHÔNG nạp chồng.

Overloaded operator định nghĩa:

public static Box operator+ (Box b, Box c) { }

Ví dụ

Ví dụ Operator Overloading:

using System; 
namespace OperatorOvlApplication { 
    class Box { 
        private double length; 
        private double breadth; 
        private double height; 
        public double getVolume() { return length * breadth * height; } 
        public void setLength(double len) { length = len; } 
        public void setBreadth(double bre) { breadth = bre; } 
        public void setHeight(double hei) { height = hei; } 
        // Overload + operator to add two Box objects. 
        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(); 
            Box Box2 = new Box(); 
            Box Box3 = new Box(); 
            double volume = 0.0; 
            Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); 
            Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); 
            volume = Box1.getVolume(); 
            Console.WriteLine("Volume of Box1 : {0}", volume); 
            volume = Box2.getVolume(); 
            Console.WriteLine("Volume of Box2 : {0}", volume); 
            // Add two objects: 
            Box3 = Box1 + Box2; 
            volume = Box3.getVolume(); 
            Console.WriteLine("Volume of Box3 : {0}", volume); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Giải thích: Box3 = Box1 + Box2 gọi operator+, cộng từng chiều: length=18, breadth=20, height=15 → Volume=18*20*15=5400.