如何获取源文件名和类型成员的行号?

考虑到调试数据文件可用(PDB)并使用System.Reflection或其他类似框架(如Mono.Cecil) ,如何以编程方式检索源文件名和类型或类型成员的行号声明。

例如,假设您已将此文件编译为程序集:

C:\ MyProject的\ Foo.cs

1: public class Foo 2: { 3: public string SayHello() 4: { 5: return "Hello"; 6: } 7: } 

怎么做这样的事情:

 MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello"); string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist! int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist! 

sourceFileName将包含“C:\ MyProject \ Foo.cs”,sourceLineNumber将等于3。

更新: System.Diagnostics.StackFrame确实能够获取该信息,但仅限于当前执行调用堆栈的范围。 这意味着必须首先调用该方法。 我想获得相同的信息,但不调用类型成员。

最新方法:

 private static void Log(string text, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0) { Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text); } 

新的Framework API在运行时填充参数(标有特殊属性),请参阅我对这个SO问题的回答

通过使用CCI元数据项目提供的PDB阅读器,可以提取给定类型成员的代码位置。 请参阅OSS Gallio项目源代码中的示例实现。

您可以在以下链接中找到一些帮助:

获取文件和行号而不部署PDB文件也发现以下post

“嗨马克,

以下将为您提供代码的行号(在源文件中):

 Dim CurrentStack As System.Diagnostics.StackTrace MsgBox (CurrentStack.GetFrame(0).GetFileLineNumber) 

如果您有兴趣,可以了解您所处的例行程序以及所有来电者。

 Public Function MeAndMyCaller As String Dim CurrentStack As New System.Diagnostics.StackTrace Dim Myself As String = CurrentStack.GetFrame(0).GetMethod.Name Dim MyCaller As String = CurrentStack.GetFrame(1).GetMethod.Name Return "In " & Myself & vbCrLf & "Called by " & MyCaller End Function 

如果你想要一个通用的错误例程,这可以非常方便,因为它可以得到调用者的名字(这将是错误发生的地方)。

此致,Fergus MVP [Windows开始按钮,关机对话]“

使用上面解释的方法之一,在属性的构造函数内,您可以提供可能具有属性的所有内容的源位置 – 例如类。 请参阅以下属性类:

 sealed class ProvideSourceLocation : Attribute { public readonly string File; public readonly string Member; public readonly int Line; public ProvideSourceLocation ( [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0) { File = file; Member = member; Line = line; } public override string ToString() { return File + "(" + Line + "):" + Member; } } [ProvideSourceLocation] class Test { ... } 

你可以编写例如:

 Console.WriteLine(typeof(Test).GetCustomAttribute(true)); 

输出将是:

 a:\develop\HWClassLibrary.cs\src\Tester\Program.cs(65): 

以下URL中的代码示例提供了一个类,您可以轻松修改该类以获取您所需的信息:

http://blogs.msdn.com/rmbyers/pages/code-sample-stacktrace-with-manual-symbol-lookup.aspx