注释用于帮助我们理解代码块。它们是人类可读的文字,旨在使代码易于理解。注释完全被编译器忽略。
在 C# 中,有 3 种类型的注释:
- 单行注释(
//
) - 多行注释(
/* */
) - XML 注释(
///
)
单行注释
单行注释以双斜杠//
开头。编译器会忽略从//
到行尾的所有内容。例如,
int a = 5 + 7; // Adding 5 and 7
这里,Adding 5 and 7
是注释。
示例 1:使用单行注释
// Hello World Program
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args) // Execution Starts from Main method
{
// Prints Hello World
Console.WriteLine("Hello World!");
}
}
}
上面的程序包含 3 个单行注释。
// Hello World Program // Execution Starts from Main method
和
// Prints Hello World
单行注释可以写在单独的一行,也可以与代码写在同一行。但是,建议将注释写在单独的一行。
多行注释
多行注释以/*
开头,以*/
结尾。多行注释可以跨越多行。
示例 2:使用多行注释
/*
This is a Hello World Program in C#.
This program prints Hello World.
*/
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
/* Prints Hello World */
Console.WriteLine("Hello World!");
}
}
}
上面的程序包含 2 个多行注释。
/* This is a Hello World Program in C#. This program prints Hello World. */
和
/* Prints Hello World */
在这里,我们可能已经注意到,多行注释不强制要求跨越多行。/* ... */
可以用来代替单行注释。
XML 文档注释
XML 文档注释是 C# 的一项特色功能。它以三重斜杠///
开头,用于分类地描述一段代码。这是通过在注释中使用 XML 标签来完成的。然后,这些注释用于创建单独的 XML 文档文件。
如果您不熟悉 XML,请参阅什么是 XML?
示例 3:使用 XML 文档注释
/// <summary>
/// This is a hello world program.
/// </summary>
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
上面程序中使用的 XML 注释是:
/// <summary> /// This is a hello world program. /// </summary>
生成的 XML 文档(.xml 文件)将包含:
<?xml version="1.0"?> <doc> <assembly> <name>HelloWorld</name> </assembly> <members> </members> </doc>
如果您有兴趣了解更多信息,请访问XML 文档注释。
正确使用注释
注释用于解释代码的一部分,但不应过度使用。
例如
// Prints Hello World Console.WriteLine("Hello World");
在上面的示例中使用注释是不必要的。该行打印 "Hello World" 是显而易见的。在这种情况下应避免使用注释。
- 相反,注释应在程序中用于解释复杂的算法和技术。
- 注释应简短明了,而不是冗长的描述。
- 经验法则:使用注释来解释为什么比解释如何更好。