C# 注释
C# 注释
在本文中,我们将了解 C# 注释、不同风格的注释,以及为什么以及如何在程序中使用它们。
程序中使用注释来帮助我们理解一段代码。它们是人类可读的单词,旨在使代码可读。编译器完全忽略注释。
在 C# 中,有 3 种类型的注释:
- 单行注释 (
//
) - 多行注释 (
/* */
) - XML 注释 (
///
)
单行注释
单行注释以双斜杠 //
开头 .编译器会忽略 //
之后的所有内容 到行尾。例如,
int a = 5 + 7; // Adding 5 and 7
这里,Adding 5 and 7
是评论。
示例一:使用单行注释
// 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。在这种情况下应避免评论。
- 应该在程序中使用注释来解释复杂的算法和技术。
- 评论应该简短而中肯,而不是冗长的描述。
- 根据经验,最好解释一下为什么 而不是如何 , 使用评论。
C语言