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

ส่วนประกอบหลักของโปรแกรม C#

ส่วนประกอบหลักของโปรแกรม C#

โครงสร้างพื้นฐานของโปรแกรม C# ประกอบด้วย 7 ส่วนหลัก

7 ส่วนประกอบ

  1. Namespace Declaration - กลุ่มคลาสที่เกี่ยวข้อง (namespace Demo)
  2. Class Declaration - แม่แบบของอ็อบเจกต์ (class Program)
  3. Class Methods - พฤติกรรมของคลาส (Main, Print, etc.)
  4. Class Attributes/Fields - ข้อมูล/สถานะ (int x;, string Name {get;set;})
  5. Main Method - Entry Point (static void Main(string[] args))
  6. Statements & Expressions - คำสั่งและนิพจน์ (x = 1;, Console.WriteLine())
  7. Comments - คำอธิบายโค้ด (//, /* */, ///)

ตัวอย่างโปรแกรม Hello World


using System;                    // 1. Using Directive (Include Namespace)
namespace Demo                   // 2. Namespace Declaration
{
    class Program                // 3. Class Declaration
    {
        static void Main(string[] args)  // 4. Main Method (Entry Point)
        {
            // 5. Statement/Expression
            Console.WriteLine("Our first program in C#!");
            Console.ReadKey();   // Statement
        }
    }                            // End Class
}                                // End Namespace

ผลลัพธ์


Our first program in C#!

คำอธิบายแต่ละบรรทัด

  • using System; - นำเข้ Namespace System (มี Console, String, Math, etc.)
  • namespace Demo - กำหนด Scope ป้องกันชื่อชนกัน
  • class Program - กำหนด Type ใหม่ ชื่อ Program
  • static void Main(string[] args) - จุดเริ่มต้นของโปรแกรม static = เรียกได้โดยไม่ต้อง new, void = ไม่คืนค่า, string[] args = Command-line Arguments
  • Console.WriteLine(...) - เรียก Static Method ของ Class Console ใน Namespace System

โครงสร้างไฟล์จริง (Modern C#)


// Program.cs (Top-level Statements - C# 9+)
using System;

Console.WriteLine("Hello, World!"); // ไม่ต้อง Main, Namespace, Class

Entry Point แบบเต็ม (C# 7.1+)


// async Main
static async Task Main(string[] args) { ... }

// Return int (Exit Code)
static int Main(string[] args) { return 0; }

// Multiple Entry Points (เลือกได้ใน Project Settings)