Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sử dụng GetValue() của lớp Array trong C#


Phương thức Array.GetValue() lấy giá trị tại vị trí chỉ định trong mảng. Chỉ số là số nguyên 32-bit.

Ví dụ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Tạo mảng 2 chiều 3x6
            Array arr = Array.CreateInstance(typeof(String), 3, 6);
            
            // Gán giá trị
            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 rows = arr.GetLength(0);
            int cols = arr.GetLength(1);
            
            // Lấy giá trị bằng GetValue
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                    Console.WriteLine(arr.GetValue(i, j) ?? "null");
            }
            
            Console.ReadLine();
        }
    }
}

Kết quả

One
Two
Three
Four
Seven
Eight
Five
Six
null
null
null
null
null
null
null
null
null
null

(18 phần tử: 3 hàng × 6 cột, 8 có giá trị, 10 null)

Overloads