注释的写法

好的注释可以让其他人快速理解代码的意义。

这不仅有利于文档生成,还可解释特殊逻辑,避免口口相传的麻烦。

好的注释是补充信息,而不是翻译。倘若方法名、字段名是规范清晰的,注释应当专注于解释业务、决策。

以一个非常重要的API方法为例:

  /// <summary>
  /// 创建形位标注
  /// </summary>
  /// <remarks>
  /// <para>
  /// 这个方法需要传入形位数组,并且可以传入<see cref="IPositionDimension"/>、<see cref="ISizeDimensionBase"/>、<see cref="IDatumBase"/> (这三个参数默认为<see langword="null"/>)<br/>
  /// 如果<see cref="IPositionDimension"/>不为空,则形位标注附着在距离尺寸上面。<br/>
  /// 生成成功,则返回<see langword="true"/>,否则为<see langword="false"/>
  /// </para>
  /// </remarks>
  /// <example>
  /// <para>以下示例演示了如何在多种情况下使用此方法创建形位标注。</para>
  /// <code lang="csharp">
  /// // 示例 1:仅创建形位标注,不关联任何尺寸或基准
  /// bool result1 = App.CreateGeoAnnotations(null, null, null, geometricTolerances);
  /// 
  /// // 示例 2:创建形位标注并关联位置尺寸
  /// bool result2 = App.CreateGeoAnnotations(positionDimension, null, null, geometricTolerances);
  /// 
  /// // 示例 3:创建形位标注并关联大小尺寸
  /// bool result3 = App.CreateGeoAnnotations(null, sizeDimension, null, geometricTolerances);
  /// 
  /// // 示例 4:创建形位标注并关联基准符号
  /// bool result4 = App.CreateGeoAnnotations(null, null, datumBase, geometricTolerances);
  /// 
  /// // 示例 5:位置尺寸、大小尺寸、基准符号、形位标注一起创建
  /// bool result5 = App.CreateGeoAnnotations(positionDimension, sizeDimension, datumBase, geometricTolerances);
  /// </code>
  /// </example>
  /// <param name="positionDimension">距离尺寸标注</param>
  /// <param name="sizeDimension">大小尺寸标注</param>
  /// <param name="datumBase">基准标注</param>
  /// <param name="geometrictolerances">形位标注</param>
  bool CreateGeoAnnotations(IPositionDimension positionDimension = null, ISizeDimensionBase sizeDimension = null, IDatumBase datumBase = null, params IGeometricTolerance[] geometrictolerances);
        
  • <summary>应当简短写出摘要

  • 换行可以用<br/>

  • <remarks>是详细说明标签,<para>表示段落

  • 在注释中镶嵌关键字/类型,可用交叉引用标签<see>

    <see cref="成员名"/> <!-- 代码元素 -->
    <see langword="关键字"/> <!-- C# 关键字 -->

  • cref属性规则:

    <see cref="T:System.String"/> <!-- 类型:T:前缀 -->
    <see cref="M:System.Math.Max"/> <!-- 方法:M:前缀 -->
    <see cref="P:System.DateTime.Now"/><!-- 属性:P:前缀 -->
    <see cref="F:System.Int32.MaxValue"/><!-- 字段:F:前缀 -->

  • <example> 示例

完整结构总结:

/// <summary>
/// [简要描述 - 显示在智能提示]
/// </summary>
/// <remarks>
/// <para>
/// [详细描述第一段]
/// 可以包含<see cref="TypeName"/>引用和<br/>换行。
/// </para>
/// <para>
/// [详细描述第二段]
/// </para>
/// </remarks>
/// <example>
/// <para>[示例描述]</para>
/// <code lang="csharp">
/// // 示例代码
/// var result = Method(param1, param2);
/// </code>
/// </example>
/// <param name="param1">[参数1描述]</param>
/// <param name="param2">[参数2描述]</param>
/// <returns>[返回值描述]</returns>
/// <exception cref="ExceptionType">[异常描述]</exception>
posted @ 2026-04-01 14:44  hélium  阅读(14)  评论(0)    收藏  举报