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

Prefix Operator ใน C# คืออะไร

Prefix Increment/Decrement (++a, --a) เพิ่ม/ลดค่าก่อน แล้วค่อยคืนค่าใหม่

พฤติกรรม

int a = 10;
int b = ++a;  // a = 11, b = 11 (เพิ่มก่อน แล้วคืนค่า)

int x = 10;
int y = --x;  // x = 9, y = 9 (ลดก่อน แล้วคืนค่า)

โค้ดตัวอย่าง

using System;

class Program
{
    static void Main()
    {
        int a, b;
        a = 10;
        
        Console.WriteLine(++a); // แสดง 11 (ค่าใหม่)
        b = a;                  // b = 11
        Console.WriteLine(a);   // 11
        Console.WriteLine(b);   // 11
    }
}

ผลลัพธ์

11
11
11

Prefix vs Postfix สรุป

Codea เริ่มต้นค่าที่ได้ (b)a หลังจบ
b = ++a101111
b = a++101011
b = --a1099
b = a--10109

Best Practice

ใช้ Prefix (++i) ใน Loop Condition ปกติ เพราะมีประสิทธิภาพดีกว่าเล็กน้อย (ไม่ต้องสร้าง Temp Copy) แม้ Compiler สมัยใหม่จะ Optimize ให้เหมือนกันก็ตาม

// แนะนำ
for (int i = 0; i < n; ++i) { }

// ทำงานได้เหมือนกัน
for (int i = 0; i < n; i++) { }