หากต้องการตั้งค่าหลายค่าให้เป็นตัวแปรเดียวกัน ให้ใช้อาร์เรย์ใน C# สมมติว่าแทนที่จะรับ 5 ตัวแปร ให้ตั้งค่า 5 ตัวแปรเหล่านี้โดยใช้อาร์เรย์ในตัวแปรเดียว
ต่อไปนี้คือตัวอย่างการตั้งค่าสามค่าให้เป็นตัวแปรเดียวด้วยอาร์เรย์สตริง -
string[] arr = new string[3];
ให้เราเริ่มต้นมัน -
string[] arr = new string[3] {"one", "two", "three"}; ต่อไปนี้เป็นตัวอย่างที่สมบูรณ์ −
ตัวอย่าง
using System;
public class Demo {
static void Main(string[] args) {
string[] arr = new string[3] {"one", "two", "three"};
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine("Values: " + arr[i]);
}
Console.ReadKey();
}
} ผลลัพธ์
Values: one Values: two Values: three