Java 有 JavaDoc,可以從原始碼直接pert== 出 HTML 文件。C# 也有對應機制,差別是它輸出的是 XML 而不是 HTML——多這一層間接,反而讓後續處理變得靈活:同一份註解資料可以轉成 HTML、PDF 或任何你想要的格式。
要啟用這個功能,註解必須以三個斜線(///)開頭,也就是 XML Doc Comment。在 /// 之後可以使用預定義標籤描述程式碼,也可以自訂標籤——自訂的標籤會原封不動地進入最終的文件檔,留給後續的 XSLT 處理。
<c><code><example><exception><include><list><para><param>name 屬性)。<paramref><permission><remarks><returns><see><seealso><summary><value>為最常見的 Hello World 主控台程式加上註解:
using System;
namespace HelloWorld
{
/// <summary>
/// Sample Hello World in C#
/// </summary>
public class HelloWorld
{
/// <summary>
/// Console Application Entry Point
/// /// <param name="args">Command Line Arguments</param>
/// <returns>Status code of 0 on successful run</returns>
/// </summary>
public static int Main(string[] args)
{
System.Console.WriteLine("HelloWorld");
string name = System.Console.ReadLine();
return(0);
}
}
}
然後在呼叫 csc 時加上 /doc 選項,指定輸出的 XML 檔名:
csc /doc:HelloWorld.xml helloworld.cs
產生的文件大致如下:
<?xml version="1.0"?>
<doc>
<assembly>
<name>XMLComment</name>
</assembly>
<members>
<member name="T:HelloWorld.HelloWorld">
<summary>
Sample Hello World in C#
</summary>
</member>
<member name="M:HelloWorld.HelloWorld.Main(System.String[])">
<summary>
Console Application Entry Point
<param name="args">Command Line Arguments</param>
<returns>Status code of 0 on successful run</returns>
</summary>
</member>
</members>
</doc>
注意 member name 的命名慣例:T: 前綴代表型別,M: 代表方法(後面接參數型別簽章),此外還有 P:(屬性)、F:(欄位)、E:(事件)等。這組前綴是後續用 XPath 查詢文件的索引鍵。
兩條路。第一條是自己寫一份 XSLT,把產生的 XML 轉成你想要的樣板——這也是當年最主流的做法,因為輸出完全可控。第二條是直接用 Visual Studio .NET:在【工具】選單中執行「建立註解 Web 頁面」,它就會替整個專案或方案產生一整套說明頁面,省去自己維護樣式表的成本。
如果團隊已在用 Sandcastle 或 DocFX 這類工具,同樣是吃這份 XML,只是樣式與網站骨架更現代。重點不變:/// 註解寫得完整,文件品質就有下限保障;寫得潦草,再好的工具也救不回來。