如何获取源文件名和类型成员的行号? [英] How to get the source file name and the line number of a type member?

查看:107
本文介绍了如何获取源文件名和类型成员的行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Considering that the debug data file is available (PDB) and by using either System.Reflection or another similar framework such as Mono.Cecil, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared.

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

For example, let's say you have compiled this file into an assembly:

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

sourceFileName would contain "C:\MyProject\Foo.cs" and sourceLineNumber be equal to 3.

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

Update: System.Diagnostics.StackFrame is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.

推荐答案

最新方法:

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 在运行时填充参数(带有特殊属性的参数),
我对此问题的回答

New Framework API which populates arguments (marked with special attributes) at runtime, see more in my answer to this SO question

这篇关于如何获取源文件名和类型成员的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆