พื้นฐาน C#

อาร์เรย์

อาร์เรย์เก็บค่าชนิดเดียวกันจำนวนคงที่ แต่ละค่าเข้าถึงด้วยดัชนีที่เริ่มจาก 0

ทำงานอย่างไร

สร้าง อ่าน แก้ไข วนดู และเรียงลำดับอาร์เรย์ใน C# รวมถึงอาร์เรย์สองมิติ

Length บอกขนาด และ ^1 อ่านสมาชิกตัวสุดท้าย foreach ไล่ดูทุกสมาชิก Array.Sort เรียงในที่เดิม new int[3] เริ่มด้วยศูนย์ และ int[,] สร้างตารางที่เข้าถึงด้วยแถวและคอลัมน์

ดูการทำงาน

คลิกที่ช่องหรือเลื่อนแถบเพื่อเลือก index ลองแทรกหรือลบเพื่อดูว่าทำไมสมาชิกตัวถัดไปทั้งหมดต้องเลื่อน

ตัวอย่าง C# ที่รันได้

C#
รันโค้ด →
Program.cs
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // An array has a fixed length set when it is created.
        int[] scores = { 72, 95, 88, 64 };
        Console.WriteLine($"Length: {scores.Length}");
        Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");

        scores[3] = 70;  // elements can be changed, the length cannot

        int sum = 0;
        foreach (int score in scores)
        {
            sum += score;
        }
        Console.WriteLine($"Sum: {sum}, average: {sum / (double)scores.Length}");

        // Array.Sort sorts in place; string.Join prints the elements.
        Array.Sort(scores);
        Console.WriteLine($"Sorted: {string.Join(", ", scores)}");
        Console.WriteLine($"Max: {scores.Max()}");

        // new int[3] creates an array of zeros.
        int[] counts = new int[3];
        counts[1] = 5;
        Console.WriteLine($"Counts: {string.Join(" ", counts)}");

        // A 2D array is indexed by row and column.
        int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine($"grid[1, 2] = {grid[1, 2]}");
    }
}
ผลลัพธ์ที่คาดหวัง
Length: 4
First: 72, last: 64
Sum: 325, average: 81.25
Sorted: 70, 72, 88, 95
Max: 95
Counts: 0 5 0
grid[1, 2] = 6

ฝึกกับดีบักเกอร์

ตั้ง breakpoint ที่การกำหนดค่าหรือเงื่อนไขสำคัญ กด Debug แล้วดูค่าตัวแปรภายในก่อนไปยังบรรทัดถัดไป

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด