在 C# XML 文档注释中使用 <code> 和 <example> 标签
介绍
代码文档描述了软件代码的意图。这包括类及其成员的意图或描述、参数和预期结果或返回值。XML 代码注释必须紧接在用户定义类型(例如类、接口或委托)或其成员(例如字段、属性、方法或事件)之前。Visual Studio 和 VS Code 的 IntelliSense 功能可以利用 XML 代码注释来显示有关类型或成员的信息;此信息来自您在代码文档中输入的内容。.NET 编译器有一个选项,可以读取 XML 文档注释并从中生成 XML 文档。此 XML 文档可以提取到单独的 XML 文件中。
XML 文档注释以///开头,可以包含为注释赋予特殊含义的推荐标签。其中两个推荐标签是<code>和<example>,我们将在本指南中介绍它们。
标签
这用于指定一个代码片段,该片段用于提供如何使用类型或类型的成员的示例。换句话说,它为文档提供了一个代码块。此代码块可以在 Visual Studio 的 IntelliSense 中使用特殊字体和缩进显示。以下是使用此标记的示例:
class Account
{
public Account(int accountNo, int balance)
{
AccountNo = accountNo;
Balance = balance;
}
public int AccountNo { get; set; }
public int Balance { get; set; }
///<summary>Credit account with amount passed as parameter</summary>
///<code>
///var account = new Account(10, 2000);
///account.Credit(5000);
///</code>
public void Credit(int amount)
{
Balance = amount + Balance;
}
}
The Credit() method has the XML comments. Between the opening and closing tags for <code>, we put the code we'd want to add to our method description.
Tag
This tag allows example code within a comment to specify how a method or other library member may be used. This would also involve the use of the <code> tag. You can put a description between the opening and closing tags. Here's an example code following from our previous code:
class Account
{
public Account(int accountNo, int balance)
{
AccountNo = accountNo;
Balance = balance;
}
public int AccountNo { get; set; }
public int Balance { get; set; }
///<summary>Credit account with amount passed as parameter</summary>
///<example>After class initialisation, call this method:
///<code>
///var account = new Account(10, 2000);
///account.Credit(5000);
///</code>
///</example>
public void Credit(int amount)
{
Balance = amount + Balance;
}
}
In VS Code it'll show you IntelliSense similar to this:
Wrap Up
XML code comments can be extremely useful in helping you, or other programmers who will use your code, to understand the code better. We looked at the <code> and <example> recommended tags which provides a way to document code examples. You saw how we can see this information through the IntelliSense. Use XML documentation comments as much as possible and give more meaning to your code. See the C# documentation for more recommended tags.
免责声明:本内容来源于第三方作者授权、网友推荐或互联网整理,旨在为广大用户提供学习与参考之用。所有文本和图片版权归原创网站或作者本人所有,其观点并不代表本站立场。如有任何版权侵犯或转载不当之情况,请与我们取得联系,我们将尽快进行相关处理与修改。感谢您的理解与支持!
请先 登录后发表评论 ~