开发者

Is it possible to retrieve file info via reflection in C#?

Say you've got a MethodInfo, or any other sub-class of MemberInfo for that matter, in C#. Is it possible to retrieve the name of the file it was declared in and possibly the line numbers for where the declaration starts? This information has to exist somewhere in the deb开发者_JAVA技巧ug-mode metadata since creating an instance of StackTrace will give you that information. Should I be looking in System.Diagnostics instead of System.Reflection?


The information about line numbers is coming from symbol files (or "program database" .pdb) typically. Tools like FxCop use the symbol file to link the IL back to the source code. I googled the following API for you: http://msdn.microsoft.com/en-us/library/system.diagnostics.symbolstore.aspx


You should use the System.Diagnostics Symbol classes to pull information from the .pdb files. Here is a good blog on it

Something like this might work:

using System;
using System.Diagnostics;

class Foo
{
static void Main()
{
    SmallFunc();
}

static void SmallFunc()
{
    PrintStack();
}
static void PrintStack()
{
    StackTrace st = new StackTrace(true); // true means get line numbers.
    foreach(StackFrame f in st.GetFrames()) {
        Console.Write(f);
    }
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜