在C#使用XML注釋 選擇自 lotusswan 的 Blog
2024-09-05 20:55:46
供稿:網友
菜鳥學堂:
在c#使用xml注釋
簡介
大多數程序員可能都聽說過java自帶的一個工具javadoc;使用它可以自動地為你的代碼生成html文檔。c#和c#編譯器也有類似的功能,不過它生成的是xml,而不是直接生成html。不過使用xml會使得文檔更加靈活。
注釋語法
為了使用c#提供的xml注釋功能,你的注釋應該使用特殊的注釋語法(///)開頭。在///之后,你可以使用預先定義的標簽注釋你的代碼,也可以插入你自己定義的標簽。你定制的標簽將會在隨后加入到生成的注釋文檔中。
預定義的標簽 用處
<c> 將說明中的文本標記為代碼
<code> 提供了一種將多行指示為代碼的方法
<example> 指定使用方法或其他庫成員的示例
<exception> 允許你指定可能發生的異常類
<include> 允許你引用描述源代碼中類型和成員的另一文件中的注釋, 使用 xml xpath 語法來描述你的源代碼中的類型和成員。
<list> 向xml注釋文檔中插入一個列表
<para> 向xml注釋文檔中插入一個段落
<param> 描述一個參數
<paramref> 提供了一種指示一個詞為參數的方法
<permission> 允許你將成員的訪問許可加入到文檔中
<remarks> 用于添加有關某個類型的信息
<returns> 描述返回值
<see> 指定鏈接
<seealso> 指定希望在“請參見”一節中出現的文本
<summary> 類型或類型成員的通用描述
<value> 描述屬性
例子
下面的例子為我們常見的helloworld控制臺應用程序添加注釋:
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);
}
}
}
為生成xml注釋文檔,我們在調用csc編譯源代碼時使用/doc選項:
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>
html頁面
你可能會問自己:我應該如何才能得到具有良好格式的html頁面呢?很簡單,你可以編寫自己的xsl來轉換生成的xml注釋文檔,或者使用visual studio.net開發工具。通過使用vs.net的【工具】菜單中的【生成注釋web頁】,你可以得到一系列詳細說明你的項目或解決方案的html頁面。下面就是通過vs.net生成的注釋helloworld程序的html頁面快照: