Skip to content

ZH TW CSharp Classes

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

類別、物件和建構函數

手冊C# · 範例UO

類別描述物件的狀態和行為。 new 建立一個實例,建構函式設定初始狀態,欄位儲存數據,屬性控制訪問,方法執行操作。 this 表示目前實例。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
var player = new Player();
System.Console.WriteLine(player.Name);
class Player { public string Name = "Archer"; }

結果:

Archer
sealed class Report
{
    public string Name { get; }
    public int Count { get; private set; }
    public Report(string name) => Name = name;
    public void Add() => Count++;
    public override string ToString() => $"{Name}: {Count}";
}

var report = new Report("Attempts");
report.Add();
report.Add();
UO.Print(report.ToString());

正常情況下 .cs- 項目類型可以方便地劃分為文件。在 .csx 你可以宣告自己的類型,但是類別內部的程式碼不接收對象 UO 自動:給他 API 或明確所需的委託。

sealed class MessageWriter
{
    private readonly Action<string> write;
    public MessageWriter(Action<string> write) => this.write = write;
    public void Send(string text) => write(text);
}

var writer = new MessageWriter(text => UO.Print(text));
writer.Send("A class uses the current session API");

官方文件:類別、物件和建構子 - Microsoft Learn。

Clone this wiki locally