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

Các phần chính của chương trình C#

Một chương trình C# cơ bản bao gồm các thành phần sau (theo thứ tự thông thường):

  1. Using Directives (using): Nhập namespace.
  2. Namespace Declaration: Tổ chức code, tránh xung đột tên.
  3. Class/Struct/Record/Interface Declaration: Định nghĩa kiểu.
  4. Members: Fields, Properties, Methods, Constructors, Events...
  5. Entry Point (Main): Điểm bắt đầu thực thi.
  6. Statements & Expressions: Logic chương trình.
  7. Comments: Chú thích (//, /* */, /// XML doc).

Ví dụ chương trình tối thiểu

// 1. Using directive
using System;

// 2. Namespace
namespace MyApp
{
    // 3. Class declaration
    class Program
    {
        // 4. Members (field, property, method)
        static string Greeting = "Hello, C#!";
        
        static void SayHello(string name)
        {
            Console.WriteLine($"{Greeting} {name}");
        }
        
        // 5. Entry Point - Main method
        static void Main(string[] args)
        {
            // 6. Statements
            SayHello("World");
            
            // Expression
            int sum = 1 + 2;
            
            // 7. Comment
            // Đây là single-line comment
            /* Đây là multi-line comment */
        }
    }
}

Kết quả

Hello, C#! World

Chi tiết các phần

1. Using Directives

using System;              // Namespace cơ bản
using System.Collections.Generic; // Generic collections
using System.Linq;         // LINQ
using MyLib = MyCompany.MyLibrary; // Alias (tránh xung đột tên)
using static System.Console; // Static import (WriteLine thay Console.WriteLine)

2. Namespace

  • Container logic cho types.
  • Có thể lồng: namespace A.B.C hoặc namespace A { namespace B { } }.
  • File-scoped namespace (C# 10+): namespace MyApp; (toàn file, không brace).

3. Type Declaration

  • class: Reference type, inheritance, nullable.
  • struct: Value type, không kế thừa (ke thừa interface), stack-friendly.
  • record / record struct (C# 9+): Immutable data type, value equality, with-expression.
  • interface: Contract, multiple implementation.

4. Main Method (Entry Point)

SignatureMô tả
static void Main()Không tham số, không trả về
static void Main(string[] args)Nhận command-line args
static int Main()Trả về exit code
static int Main(string[] args)Full signature
static async Task Main()Async entry point (C# 7.1+)
static async Task<int> Main()Async + exit code

5. Top-level Statements (C# 9+)

Có thể bỏ qua class/Program/Main hoàn toàn cho script/simple app:

// Program.cs - toàn bộ file
using System;

Console.WriteLine("Hello from top-level statements!");
var name = args.Length > 0 ? args[0] : "World";
Console.WriteLine($"Hello, {name}!");

Compiler tự generate class Program + Main.

Tóm tắt

Hiểu rõ cấu trúc giúp tổ chức code clean, hiểu compiler xử lý như thế nào, và tận dụng tính năng mới (top-level statements, file-scoped namespace, records).