首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 基本語法完整指南:程式結構、命名規則、關鍵字、註解、Main 入口點與編譯執行

     編輯:C# 入門

C# 基本語法完整指南:程式結構、命名規則、關鍵字、註解、Main 入口點與編譯執行

掌握 C# 基本語法是踏上 .NET 開發旅程的第一步。本文涵蓋程式基本結構、命名慣例、關鍵字、註解、Main 方法、編譯執行流程,並提供實用的程式碼風格建議。

最小 C# 程式結構

// 1. using 指令:引入命名空間
using System;

// 2. 命名空間宣告:邏輯分組
namespace HelloWorld {
    // 3. 類別宣告
    public class Program {
        // 4. Main 方法:程式進入點
        public static void Main() {
            // 5. 陳述式
            Console.WriteLine("Hello, World!");
        }
    }
}

現代簡化語法

最上層陳述式

.NET 6+ (C# 9+) 允許省略 Main、類別、命名空間:

// Program.cs 完整內容
using System;
Console.WriteLine("Hello, World!");

編譯器自動產生 Program 類別與 Main 方法。

檔案範圍命名空間

C# 10+:

namespace MyApp; // 整個檔案屬於此命名空間,無需大括號

public class MyClass { }

命名規則與慣例

元素慣例範例
命名空間PascalCaseMyCompany.MyProduct.Module
類別/結構/介面/列舉/委派PascalCaseCustomer, IRepository, OrderStatus
方法/屬性/事件/公開欄位PascalCaseCalculateTotal, FirstName
區域變數/參數camelCaseitemCount, userName
私有欄位_camelCase_firstName
常數/readonly 靜態欄位PascalCaseMaxRetries
型別參數T / TDescriptorT, TKey, TValue

規則:字母/底線開頭、可含字母/數字/底線、不可為關鍵字 (可加 @ 前綴)、區分大小寫。

關鍵字完整分類

保留關鍵字

abstract as base bool break byte case catch char checked class const
continue decimal default delegate do double else enum event explicit
extern false finally fixed float for foreach goto if implicit in int
interface internal is lock long namespace new null object operator out
override params private protected public readonly ref return sbyte sealed
short sizeof stackalloc static string struct switch this throw true try
typeof uint ulong unchecked unsafe ushort using virtual void volatile while

內容關鍵字

add alias ascending descending dynamic from get global group into join
let orderby partial remove select set value var when where yield

內容關鍵字在特定語境有特殊意義,其他地方可作識別碼 (如 var x = 1;)。

註解

// 單行註解
/* 多行註解
   可跨多行 */

/// 
/// XML 文件註解:產生 API 文件、IntelliSense 提示
/// 
/// 參數說明
/// 回傳值說明
public int Add(int x, int y) => x + y;

// 區域標記 (編輯器摺疊)
#region 初始化
// ...
#endregion

Main 方法完整簽章

// 標準
static void Main() { }

// 回傳結束代碼
static int Main() { return 0; }

// 接收命令列參數
static void Main(string[] args) { }
static int Main(string[] args) { return 0; }

// 非同步 Main (C# 7.1+)
static async Task Main() { await DoWork(); }
static async Task Main(string[] args) { return await DoWorkAsync(); }

// 多 Main 進入點:編譯器選項 /main:TypeName 指定

陳述式與運算式

  • 陳述式:執行動作,以 ; 結尾 (x = 1;, if (...) {}, return;)
  • 運算式:產生值 (x + y, Method(), new Object())
  • 運算式主體成員:=> 簡化單行實作
public int Add(int a, int b) => a + b;           // 方法
public string Name { get => _name; set => _name = value; } // 屬性
public override string ToString() => $"Person: {Name}";      // 覆寫

編譯與執行流程

.NET CLI

# 建立專案
dotnet new console -n MyApp
cd MyApp

# 編譯 (產生 dll)
dotnet build

# 執行
dotnet run

# 發布獨立執行檔
dotnet publish -c Release -r win-x64 --self-contained true

傳統 csc 編譯器

csc Program.cs           # 產生 Program.exe
csc /target:library Lib.cs # 產生 Lib.dll
csc /reference:Lib.dll App.cs # 參考組件

Visual Studio

  • F5:偵錯執行
  • Ctrl+F5:不偵錯執行
  • 建置:編譯檢查錯誤
  • 重建:清理後完整建置

程式碼風格建議

  • 一個檔案一個公開類型:檔名與類型名一致。
  • using 排序:System 優先、第三方、專案內部,字母序。
  • 大括號風格:Allman (新行) 或 K&R (同行),團隊統一。
  • 縮排 4 空格:不使用 Tab。
  • 行寬 ≤ 120 字元:超過換行。
  • 檔案編碼 UTF-8:無 BOM。
  • 啟用可為 Null 參考型別:<Nullable>enable</Nullable>。

常見問題 FAQ

Q: using 指令放在命名空間內外有差別嗎?

A: 放在 namespace 內僅影響該命名空間內的型別解析;放在外部影響整個檔案。慣例放在檔案最上方。

Q: 可以有多個 Main 方法嗎?

A: 可以,但需用 /main 指定進入點。單一專案通常只有一個。

Q: var 是關鍵字還是內容關鍵字?

A: 內容關鍵字。在 var x = 1; 中為關鍵字;var var = 1; 中第二個 var 為識別碼 (不建議)。

Q: C# 區分大小寫嗎?

A: 是。MyClass ≠ myclass ≠ MYCLASS。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved