在 C# XML 文档注释中使用 <code> 和 <example> 标签

发布日期:2026-07-15 10:41:03   来源 : 杭州电子商务研究院    浏览量 :3
杭州电子商务研究院 发布日期:2026-07-15 10:41:03  
3

介绍

代码文档描述了软件代码的意图。这包括类及其成员的意图或描述、参数和预期结果或返回值。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:

code completion intellisense.png

mouse hover intellisense.png

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.

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据