ส่วนประกอบหลักของโปรแกรม C#
โครงสร้างพื้นฐานของโปรแกรม C# ประกอบด้วย 7 ส่วนหลัก
7 ส่วนประกอบ
- Namespace Declaration - กลุ่มคลาสที่เกี่ยวข้อง (
namespace Demo) - Class Declaration - แม่แบบของอ็อบเจกต์ (
class Program) - Class Methods - พฤติกรรมของคลาส (
Main,Print, etc.) - Class Attributes/Fields - ข้อมูล/สถานะ (
int x;,string Name {get;set;}) - Main Method - Entry Point (
static void Main(string[] args)) - Statements & Expressions - คำสั่งและนิพจน์ (
x = 1;,Console.WriteLine()) - 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;- นำเข้ NamespaceSystem(มีConsole,String,Math, etc.)namespace Demo- กำหนด Scope ป้องกันชื่อชนกันclass Program- กำหนด Type ใหม่ ชื่อ Programstatic void Main(string[] args)- จุดเริ่มต้นของโปรแกรมstatic= เรียกได้โดยไม่ต้อง new,void= ไม่คืนค่า,string[] args= Command-line ArgumentsConsole.WriteLine(...)- เรียก Static Method ของ ClassConsoleใน NamespaceSystem
โครงสร้างไฟล์จริง (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)