Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

reflection - c# getting interface method comments

Say I have

    interface IFoo
    {
        /// <summary>
        /// Comments about Bar method goes here.
        /// </summary>
        void Bar();
    }

I'm using reflection to display the methods at runtime

MethodInfo[] mis = typeof(IFoo).GetMethods();

but I was wondering if I can get the comments included in <summary> </summary> for the methods. I realize that comments are just ignored my the compiler but is there anything that could be done to retrieve comments? Right now I have a seperate file that has the methods and the comments but I hate the redundancy and was wondering if there is any way to do this.

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The C# compiler csc.exe has a /doc option that outputs an external XML file having your triple-slash comments. This XML file is used by documentation generators (e.g. Sandcastle does this kind of thing).

That same option to export XML comments is available from Visual Studio. To set this compiler option in the Visual Studio development environment:

  1. Open the project's Properties page. For details, see How to: Set Project Properties (C#, J#).
  2. Click the Build property page.
  3. Modify the XML Documentation File property.

You can load up this XML file using an XML parser from the .NET framework, access the Types in it, and grab the related comments from around them.

You're right the C# compiler doesn't compile comments into the meta data. However Microsoft created triple-slash comments for export ability, so you can get a handle to them.

Instructions for processing the XML file are here on MSDN.


As an example, I enable the XML output file option and documented the following method:

/// <summary>
/// This method parses the given name for
/// capitalization.
/// </summary>
public void ParseStringCase(string name)
{
    // behaviour of method...
}

It produces the following XML in a file in the bin/ folder....

<?xml version="1.0"?>
<doc>
    <assembly>
        <name>WindowsFormsApplication3</name>
    </assembly>
    <members>
        <member name="M:WindowsFormsApplication3.Form1.ParseStringCase(System.String)">
            <summary>
            This method parses the given name for
            capitalization.
            </summary>
        </member>
    </members>
</doc>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...