65

ASP.netのメソッドのXmlコメントの要約部分をプログラムで取得する方法を探しています。

私は以前の関連する投稿を見ましたが、それらはWeb環境でそうする方法を提供していません。

サードパーティのアプリを使用できません。また、Web環境のため、VisualStudioプラグインもあまり使用されていません。

私が見つけた実用的なソリューションに最も近いものはJimBlacklerプロジェクトでしたが、それはDLLでのみ機能します。

当然、「。CSファイルを提供し、XMLドキュメントを取得する」のようなものが最適です。


現在の状況

Webサービスがあり、そのドキュメントを動的に生成しようとしています。

メソッドとプロパティを読むのは簡単ですが、各メソッドの概要を取得するのは少し面倒です。

/// <summary>
/// This Is what I'm trying to read
/// </summary>
public class SomeClass()
{
    /// <summary>
    /// This Is what I'm trying to read
    /// </summary>
    public void SomeMethod()
    {
    }
}

4

7 に答える 7

49

回避策-Program.XMLファイルと一緒にProgram.DLL/EXEのリフレクションを使用する

Visual Studioによって生成された兄弟の.XMLファイルを見ると、/ members/memberの階層がかなりフラットであることがわかります。あなたがしなければならないのは、MethodInfoオブジェクトを介してDLLから各メソッドを取得することです。このオブジェクトを取得したら、XMLを使用し、XPATHを使用して、このメソッドのXMLドキュメントを含むメンバーを取得します。

メンバーの前には文字が付いています。メソッドのXMLドキュメントの前には「M:」が付き、クラスの場合は「T:」などが付きます。

兄弟XMLをロードします

string docuPath = dllPath.Substring(0, dllPath.LastIndexOf(".")) + ".XML";

if (File.Exists(docuPath))
{
  _docuDoc = new XmlDocument();
  _docuDoc.Load(docuPath);
}

このxpathを使用して、メソッドXMLdocuを表すメンバーを取得します

string path = "M:" + mi.DeclaringType.FullName + "." + mi.Name;

XmlNode xmlDocuOfMethod = _docuDoc.SelectSingleNode(
    "//member[starts-with(@name, '" + path + "')]");

ここで、子ノードをスキャンして「///」のすべての行を探します。///要約に余分な空白が含まれている場合があります。これを使用して削除する場合は、

var cleanStr = Regex.Replace(row.InnerXml, @"\s+", " ");
于 2013-12-26T19:49:22.833 に答える
39

XMLサマリーは.NETアセンブリに保存されません。オプションで、ビルドの一部としてXMLファイルに書き出されます(Visual Studioを使用している場合)。

したがって、コンパイルされた.NETアセンブリ(.EXEまたは.DLL)でのリフレクションを介して、各メソッドのXMLサマリーを「引き出す」方法はありません。データが単にそこにないためです。データが必要な場合は、ビルドプロセスの一部としてXMLファイルを出力し、実行時にそれらのXMLファイルを解析して要約情報を取得するように、ビルド環境に指示する必要があります。

于 2013-03-24T19:12:37.663 に答える
28

System.ComponentModel.DataAnnotations.DisplayAttribute属性を使用してメソッドを「文書化」できます。

[Display(Name = "Foo", Description = "Blah")]
void Foo()
{
}

次に、リフレクションを使用して、実行時に説明をプルします。

于 2013-03-24T22:32:42.320 に答える
14

このスレッドで@OleksandrIeremenkoによって作成された削除された投稿は、私のソリューションの基礎となったこの記事https://jimblackler.net/blog/?p=49にリンクしています。

以下は、MemberInfoオブジェクトとTypeオブジェクトから拡張メソッドを作成し、要約テキストまたは使用できない場合は空の文字列を返すコードを追加する、JimBlacklerのコードの変更です。

使用法

var typeSummary = typeof([Type Name]).GetSummary();
var methodSummary = typeof([Type Name]).GetMethod("[Method Name]").GetSummary();

拡張クラス

/// <summary>
/// Utility class to provide documentation for various types where available with the assembly
/// </summary>
public static class DocumentationExtensions
{
    /// <summary>
    /// Provides the documentation comments for a specific method
    /// </summary>
    /// <param name="methodInfo">The MethodInfo (reflection data ) of the member to find documentation for</param>
    /// <returns>The XML fragment describing the method</returns>
    public static XmlElement GetDocumentation(this MethodInfo methodInfo)
    {
        // Calculate the parameter string as this is in the member name in the XML
        var parametersString = "";
        foreach (var parameterInfo in methodInfo.GetParameters())
        {
            if (parametersString.Length > 0)
            {
                parametersString += ",";
            }

            parametersString += parameterInfo.ParameterType.FullName;
        }

        //AL: 15.04.2008 ==> BUG-FIX remove “()” if parametersString is empty
        if (parametersString.Length > 0)
            return XmlFromName(methodInfo.DeclaringType, 'M', methodInfo.Name + "(" + parametersString + ")");
        else
            return XmlFromName(methodInfo.DeclaringType, 'M', methodInfo.Name);
    }

    /// <summary>
    /// Provides the documentation comments for a specific member
    /// </summary>
    /// <param name="memberInfo">The MemberInfo (reflection data) or the member to find documentation for</param>
    /// <returns>The XML fragment describing the member</returns>
    public static XmlElement GetDocumentation(this MemberInfo memberInfo)
    {
        // First character [0] of member type is prefix character in the name in the XML
        return XmlFromName(memberInfo.DeclaringType, memberInfo.MemberType.ToString()[0], memberInfo.Name);
    }
    /// <summary>
    /// Returns the Xml documenation summary comment for this member
    /// </summary>
    /// <param name="memberInfo"></param>
    /// <returns></returns>
    public static string GetSummary(this MemberInfo memberInfo)
    {
        var element = memberInfo.GetDocumentation();
        var summaryElm = element?.SelectSingleNode("summary");
        if (summaryElm == null) return "";
        return summaryElm.InnerText.Trim();
    }

    /// <summary>
    /// Provides the documentation comments for a specific type
    /// </summary>
    /// <param name="type">Type to find the documentation for</param>
    /// <returns>The XML fragment that describes the type</returns>
    public static XmlElement GetDocumentation(this Type type)
    {
        // Prefix in type names is T
        return XmlFromName(type, 'T', "");
    }

    /// <summary>
    /// Gets the summary portion of a type's documenation or returns an empty string if not available
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static string GetSummary(this Type type)
    {
        var element = type.GetDocumentation();
        var summaryElm = element?.SelectSingleNode("summary");
        if (summaryElm == null) return "";
        return summaryElm.InnerText.Trim();
    }

    /// <summary>
    /// Obtains the XML Element that describes a reflection element by searching the 
    /// members for a member that has a name that describes the element.
    /// </summary>
    /// <param name="type">The type or parent type, used to fetch the assembly</param>
    /// <param name="prefix">The prefix as seen in the name attribute in the documentation XML</param>
    /// <param name="name">Where relevant, the full name qualifier for the element</param>
    /// <returns>The member that has a name that describes the specified reflection element</returns>
    private static XmlElement XmlFromName(this Type type, char prefix, string name)
    {
        string fullName;

        if (string.IsNullOrEmpty(name))
            fullName = prefix + ":" + type.FullName;
        else
            fullName = prefix + ":" + type.FullName + "." + name;

        var xmlDocument = XmlFromAssembly(type.Assembly);

        var matchedElement = xmlDocument["doc"]["members"].SelectSingleNode("member[@name='" + fullName + "']") as XmlElement;

        return matchedElement;
    }

    /// <summary>
    /// A cache used to remember Xml documentation for assemblies
    /// </summary>
    private static readonly Dictionary<Assembly, XmlDocument> Cache = new Dictionary<Assembly, XmlDocument>();

    /// <summary>
    /// A cache used to store failure exceptions for assembly lookups
    /// </summary>
    private static readonly Dictionary<Assembly, Exception> FailCache = new Dictionary<Assembly, Exception>();

    /// <summary>
    /// Obtains the documentation file for the specified assembly
    /// </summary>
    /// <param name="assembly">The assembly to find the XML document for</param>
    /// <returns>The XML document</returns>
    /// <remarks>This version uses a cache to preserve the assemblies, so that 
    /// the XML file is not loaded and parsed on every single lookup</remarks>
    public static XmlDocument XmlFromAssembly(this Assembly assembly)
    {
        if (FailCache.ContainsKey(assembly))
        {
            throw FailCache[assembly];
        }

        try
        {

            if (!Cache.ContainsKey(assembly))
            {
                // load the docuemnt into the cache
                Cache[assembly] = XmlFromAssemblyNonCached(assembly);
            }

            return Cache[assembly];
        }
        catch (Exception exception)
        {
            FailCache[assembly] = exception;
            throw;
        }
    }

    /// <summary>
    /// Loads and parses the documentation file for the specified assembly
    /// </summary>
    /// <param name="assembly">The assembly to find the XML document for</param>
    /// <returns>The XML document</returns>
    private static XmlDocument XmlFromAssemblyNonCached(Assembly assembly)
    {
        var assemblyFilename = assembly.Location;
   
        if (!string.IsNullOrEmpty(assemblyFilename))
        {
            StreamReader streamReader;

            try
            {
                streamReader = new StreamReader(Path.ChangeExtension(assemblyFilename, ".xml"));
            }
            catch (FileNotFoundException exception)
            {
                throw new Exception("XML documentation not present (make sure it is turned on in project properties when building)", exception);
            }

            var xmlDocument = new XmlDocument();
            xmlDocument.Load(streamReader);
            return xmlDocument;
        }
        else
        {
            throw new Exception("Could not ascertain assembly filename", null);
        }
    }
}
于 2019-01-02T15:54:04.403 に答える
5

Namotion.Reflection NuGetパッケージを使用して、次の情報を取得できます。

string summary = typeof(Foo).GetXmlDocsSummary();
于 2020-01-20T14:59:55.087 に答える
1

https://github.com/NSwag/NSwag-nugetNSwag.CodeGenerationのソース-概要も取得します。使用法

var generator = new WebApiAssemblyToSwaggerGenerator(settings);<br/>
var swaggerService = generator.GenerateForController("namespace.someController");<br/>
// string with comments <br/>
var swaggerJson = swaggerService.ToJson(); 

(dllに対してILSPY逆コンパイラーを試してください。コードとコメントを確認してください)

于 2016-09-10T02:54:41.110 に答える
0

コメントを取得しようとしているソースコードにアクセスできる場合は、Roslynコンパイラプラットフォームを使用してそれを行うことができます。基本的に、すべての中間コンパイラメタデータにアクセスでき、必要な操作を実行できます。

他の人が提案しているものよりも少し複雑ですが、ニーズによってはオプションになる場合があります。

この投稿には、同様のコードサンプルがあるようです。

于 2015-08-04T21:23:03.363 に答える