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

标签 c# reflection

考虑到调试数据文件可用 (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 在运行时填充参数(用特殊属性标记), 查看更多 my answer to this SO question

关于c# - 如何获取类型成员的源文件名和行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/126094/

相关文章:

c# - 我的 Visual Studio Code 中的区域折叠不起作用

.NET 4.0 : How can I get the underlying type of a generic parameter if it is Nullable?

c# - 通过传递 Expression<Func<T, object>> 使用反射调用方法

java - 如何以编程方式检索方法的参数

performance - 设置类的私有(private)属性

c# - 托管扩展框架、拦截和动态代理

c# - 保存到 SQL Server 时附加到文件的字节

c# - 如何使用内存流将 WinForms 应用程序中的 MS Chart 插入到 Outlook 电子邮件中?

c# - Arduino 用 Visual C# 制作的软件无法正常工作

java - 从类文件中读取一行代码