好的,这是我想到的解决方案。
我在依赖属性中使用了一个特殊的XML标签,它将被XSL转换替换。虽然没有使用该标签也是可以实现的,但是Visual Studio会发出警告,因为该字段未经记录。
/// <dpdoc />
public static readonly DependencyProperty PositionProperty =
DependencyProperty.Register(...)
C# 属性的文档与平常一样,只需确保不要忘记值的描述。
public Point Position set }
在构建过程中,Visual Studio 会从这些注释中创建一个 XML 文件。通过一些 xsl 转换,dpdoc
节点会被属性文档的修改版本所替换。生成的 XML 文件与我们精心记录属性标识符的文件相同。它甚至包括一个简短的注释,说明还有另一种访问变量的方式:
public static readonly DependencyProperty PositionProperty =
DependencyProperty.Register(...)
那样的话,两个API都有适当的文档,我们不需要在代码中重复文档。可以在构建后事件中完成xsl转换或集成到文档生成过程中。
以下是xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="//dpdoc">
<xsl:variable name="propertyName" select="concat('P:', substring(../@name,3,string-length(../@name)-10))" />
<summary>
<xsl:apply-templates select="//member[@name=$propertyName]/value/node()"/>
</summary>
<xsl:apply-templates select="//member[@name=$propertyName]/*[not(self::remarks)][not(self::summary)][not(self::value)]"/>
<remarks>
<xsl:apply-templates select="//member[@name=$propertyName]/remarks/node()"/>
<para>
This dependency property can be accessed via the
<see>
<xsl:attribute name="cref"><xsl:value-of select="$propertyName"/></xsl:attribute>
</see>
property.
</para>
</remarks>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
为什么我希望这样做:
- 属性标识符(
DependencyProperty
实例)和属性本身都是公共的,因此可以合法地用于访问该属性。因此,我们有两个 API 可以访问同一个逻辑变量。
- 代码文档应该描述看不到的内容。在这种情况下,它应该描述属性的含义、值以及如何正确使用它。由于属性标识符和 C# 属性引用了相同的逻辑变量,它们具有相同的含义。
- 用户可以自由选择两种访问逻辑变量的方式,并且不必意识到另一种方式。因此,两者都必须得到适当的文档支持。
- 复制粘贴代码注释和复制粘贴代码一样糟糕。