เมธอด GetValue() ของคลาส Array ใน C# ดึงค่าที่ตำแหน่งที่ระบุในอาร์เรย์ 1 มิติ ดัชนีระบุเป็นจำนวนเต็ม 32 บิต
เราได้กำหนดค่าอาร์เรย์ก่อนด้วย Array.CreateInstance
Array arr = Array.CreateInstance(typeof(String), 3, 6);
arr.SetValue("One", 0, 0);
arr.SetValue("Two", 0, 1);
arr.SetValue("Three", 0, 2);
arr.SetValue("Four", 0, 3);
arr.SetValue("Five", 1, 4);
arr.SetValue("Six", 1, 5);
arr.SetValue("Seven", 1, 2);
arr.SetValue("Eight", 1, 3);ลูปผ่านความยาวอาร์เรย์ จะแสดงค่าทั้งหมดด้วย GetValue()
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
Console.WriteLine(arr.GetValue(i, j));ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class Program {
static void Main(string[] args) {
Array arr = Array.CreateInstance(typeof(String), 3, 6);
arr.SetValue("One", 0, 0);
arr.SetValue("Two", 0, 1);
arr.SetValue("Three", 0, 2);
arr.SetValue("Four", 0, 3);
arr.SetValue("Five", 1, 4);
arr.SetValue("Six", 1, 5);
arr.SetValue("Seven", 1, 2);
arr.SetValue("Eight", 1, 3);
int a = arr.GetLength(0);
int b = arr.GetLength(1);
// ดึงค่า
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
Console.WriteLine(arr.GetValue(i, j));
Console.ReadLine();
}
}
}ผลลัพธ์
One Two Three Four Seven Eight Five Six