2000 年 6 月,微軟發布 C# 語言與 .NET 平台。.NET 核心包含:
unsafe 才能用指標)object,需 new 配置記憶體. 運算子,null/bool 為關鍵字try-finally、布林條件判斷、變數必須初始化Java/C++ 需撰寫 getX()/setX(),C# 引入 property 語法:
// Java 風格
foo.setSize(foo.getSize() + 1);
label.getFont().setBold(true);
// C# 屬性語法
foo.Size++;
label.Font.Bold = true;
編譯器自動產生 get/set 存取器,並區分「欄位」與「屬性」。C# 要求成對出現,利於維護。
索引子本質是參數化屬性,語法使用 this[int index]:
public class Skyscraper
{
Story[] stories;
public Story this[int index]
{
get { return stories[index]; }
set { if (value != null) stories[index] = value; }
}
}
// 使用方式
Skyscraper empireState = new Skyscraper(...);
empireState[102] = new Story("The Top One", ...);
此特性源自 VB/Delphi,極大簡化集合類別的使用體驗。