Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Operator Functions (Operator Overloading) ใน C#

Operator Functions คือ เมธอดพิเศษที่กำหนดพฤติกรรมของ Operator (+, -, ==, implicit, explicit ฯลฯ) สำหรับ Custom Types เรียกว่า Operator Overloading

โครงสร้าง

public static ReturnType operator OperatorSymbol(ParameterList) {
    // Implementation
}

กฎสำคัญ

  • ต้องเป็น public static
  • อย่างน้อย 1 พารามิเตอร์ต้องเป็น Containing Type
  • ไม่สามารถ Overload =, &&, ||, ?:, new, typeof, sizeof, ., () ได้
  • บาง Operator ต้อง Overload เป็นคู่: ==/!=, </>, <=/>=
  • เมื่อ Overload ==/!= ควร Override Equals() และ GetHashCode() ด้วย

ตัวอย่างครบถ้วน: Box Class

using System;

namespace OperatorOvlApplication {
    class Box {
        public double Length { get; private set; }
        public double Breadth { get; private set; }
        public double Height { get; private set; }
        
        public Box(double l = 0, double b = 0, double h = 0) {
            Length = l; Breadth = b; Height = h;
        }
        
        public double Volume => Length * Breadth * Height;
        
        // Overload + : รวมสอง Box
        public static Box operator +(Box b1, Box b2) {
            return new Box(
                b1.Length + b2.Length,
                b1.Breadth + b2.Breadth,
                b1.Height + b2.Height
            );
        }
        
        // Overload == และ != (คู่กัน)
        public static bool operator ==(Box b1, Box b2) {
            if (ReferenceEquals(b1, null) && ReferenceEquals(b2, null)) return true;
            if (ReferenceEquals(b1, null) || ReferenceEquals(b2, null)) return false;
            return b1.Length == b2.Length && b1.Breadth == b2.Breadth && b1.Height == b2.Height;
        }
        
        public static bool operator !=(Box b1, Box b2) => !(b1 == b2);
        
        // Override Equals/GetHashCode (จำเป็นเมื่อ Overload ==/!=)
        public override bool Equals(object obj) => this == (obj as Box);
        public override int GetHashCode() => (Length, Breadth, Height).GetHashCode();
        
        // Implicit Conversion: int → Box (Cube)
        public static implicit operator Box(int size) => new Box(size, size, size);
        
        // Explicit Conversion: Box → double (Volume)
        public static explicit operator double(Box b) => b.Volume;
    }
    
    class Tester {
        static void Main() {
            Box box1 = new Box(6, 7, 5);
            Box box2 = new Box(12, 13, 10);
            
            // Operator +
            Box box3 = box1 + box2;
            Console.WriteLine($"Box3 Volume: {box3.Volume}"); // 5400
            
            // Implicit Conversion
            Box cube = 5; // int → Box(5,5,5)
            Console.WriteLine($"Cube Volume: {cube.Volume}"); // 125
            
            // Explicit Conversion
            double vol = (double)box1; // Box → double
            Console.WriteLine($"Box1 Volume as double: {vol}"); // 210
            
            // Equality
            Console.WriteLine(box1 == new Box(6, 7, 5)); // True
            Console.WriteLine(box1 != box2); // True
            
            Console.ReadKey();
        }
    }
}

Conversion Operators

ประเภทSyntaxการใช้งาน
Implicitpublic static implicit operator Target(Source s)Target t = source; (ไม่ต้อง Cast)
Explicitpublic static explicit operator Target(Source s)Target t = (Target)source; (ต้อง Cast)

แนวทางปฏิบัติ

  • Overload Operator เฉพาะที่มีความหมายชัดเจน (Mathematical/Logical Sense)
  • หลีกเลี่ยง Side Effects ใน Operator
  • Implicit Conversion: ใช้เมื่อไม่มี Data Loss และปลอดภัย
  • Explicit Conversion: ใช้เมื่ออาจมี Data Loss หรือ Exception
  • Test ความเท่ากัน (Equality) อย่างละเอียด — รวม Null Checks