当提供相同方法的多个重载时,我经常不得不重复该方法的描述,这违反了DRY并增加了维护成本:
/// <summary> /// Frobnicates all foos read from the given reader. Frobnication is a /// process where ...[lots of text]... /// </summary> /// <param name="hasBar">[Description of hasBar]</param> void FrobnicateFoo(TextReader reader,bool hasBar) { ... } /// <summary> /// Frobnicates all foos read from the given file. Frobnication is a /// process where ...[same lots of text]... /// </summary> /// <param name="hasBar">[Same description of hasBar]</param> void FrobnicateFoo(String path,bool hasBar) { ... }
如果重复具有相同目的的多个参数,则该问题变得更糟(作为示例给出“hasBar”).
我找到的一个“解决方法”是“引用”其他文档:
/// <summary> /// Frobnicates all foos read from the given reader. Frobnication is a /// process where ...[lots of text]... /// </summary> /// <param name="hasBar">[Description of hasBar]</param> void FrobnicateFoo(TextReader reader,bool hasBar) { ... } /// <summary> /// Convenience method which opens the file with a UTF-8 encoding and then /// frobnicates all foos,see FrobnicateFoo(TextReader). /// </summary> void FrobnicateFoo(String path,bool hasBar) { ... }
显然,这对于图书馆的用户来说不太方便.
是否有一些内置机制(或智能策略)可以用来避免重复并让我的方法的用户轻松生活?我主要关注IntelliSense,而不是生成的HTML文档.
解决方法
实际上有一个使用XML标签的解决方案.实际上,您在XML文件中构建文档,然后将方法链接到此XML文件.这是我编写的一个小例子.
这里的解决方案是在VB.NET中,但我想将它转换为C#并不是很困难…
首先,您需要一个标准的库定义:
''' <summary> ''' This is my First class ''' </summary> ''' <remarks></remarks> Public Class FirstClass ''' <summary> ''' This is my first method ''' </summary> ''' <param name="A">A</param> ''' <returns>True</returns> ''' <remarks></remarks> Public Function FirstMethod(A As Integer) As Boolean Return True End Function ''' <include file="DocFile.xml" path="Doc/member[@name='SecondMethod']/*" /> Public Function SecondMethod(A As Integer) As String Return "Hello" End Function ''' <include file="DocFile.xml" path="Doc/member[@name='SecondMethod']/*" /> Public Function SecondMethod(A As Integer,B As String) As String Return "Hello" End Function ''' <include file="DocFile.xml" path="Doc/member[@name='SecondMethod']/*" /> Public Function SecondMethod(A As Integer,B As String,C As Boolean) As String Return "Hello" End Function End Class
因此,课程和第一种方法的文档是“标准的”.对于SecondMethod,我提供了一个XML链接.
接下来你需要创建一个XML文件,这里称为DocFile.XML,你将在其中放置方法的文档:
<Doc> <member name="SecondMethod"> <summary> This is my second method </summary> <param name="A">a</param> <param name="B">b</param> <param name="C">c</param> <returns>A string containing "Hello"</returns> <remarks></remarks> </member> </Doc>
当你一起编译并创建文档(这里我使用SandCastle)时,它产生以下内容:
对于每种方法:
和
TLDR
>可以在XML文件中创建一次文档,并将方法链接到本文档.>您可以将许多方法链接到一个定义>案件很敏感> Visual Studio(这里我使用的是VS 2010 Express)在这个上并没有什么帮助,它不知道你在做什么.编译时,您将无法在项目的intellisense中看到它.如果您创建另一个解决方案并引用您的库,那么您将看到它.