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

ทำไมจึงใช้ Comma Operator ใน C#

Comma operator (,) ใน C# ใช้เป็นตัวคั่นในรายการอาร์กิวเมนต์ของเมธอด และยังใช้เป็นออเปอเรเตอร์ในคำสั่ง for ได้อีกด้วย

ตัวอย่างการใช้ใน for loop สำหรับ initialization

for (int i = begin, j = 1; i <= end; i++, j++)

ใช้ใน Console.WriteLine สำหรับแสดงค่า

Console.Write("{0} : {1} ", i, (char)i);

โค้ดเต็ม

using System;

class Demo {
    const int begin = 45;
    const int end = 60;
    const int line = 1;
    
    static public void Main() {
        for (int i = begin, j = 1; i <= end; i++, j++) {
            Console.Write("{0} : {1} ", i, (char)i);
            if (0 == (j % line)) {
                Console.WriteLine("");
            }
        }
    }
}

ผลลัพธ์

45 : - 46 : . 47 : / 48 : 0 49 : 1 50 : 2 51 : 3 52 : 4 53 : 5 54 : 6 55 : 7 56 : 8 57 : 9 58 : : 59 : ; 60 : <