Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...