c# - 如何从 StackTrace 获取正确的行号?

标签 c# visual-studio stack-trace

我正在编写自己的穷人测试框架。在我的控制台应用程序中,我有这个:

  static void Main(string[] args)
  {     // Line 12
     double adouble = 77;
     double expected = 70;
     TestingFramework.assertEquals<double>(expected, adouble - 7);  // Line 15
     TestingFramework.assertEquals<double>(expected, adouble - 6);  // Line 16
   }

在 TestingFramework 中我有这一行:

System.Console.WriteLine("Success, File {0}, Line {1}", 
   new System.Diagnostics.StackTrace(true).GetFrame(1).GetFileName(), 
   new System.Diagnostics.StackTrace(true).GetFrame(1).GetFileLineNumber());

但是当我运行测试时,它告诉我两个函数调用的 FileLineNumber 都是 12。此外,它给了我正确的文件名,所以我认为它引用了正确的框架。

谁能告诉我如何让它向我报告发起调用的行号(15 然后 16),而不是开括号 (12) 的行号?

谢谢。

最佳答案

附加到我的评论中,像这样:

    foreach(var frame in StackTrace.GetFrames())
    { 
        System.Reflection.MethodBase method = frame.GetMethod ( );
        Type type = method.DeclaringType;
        // If this is what I am looking for
        if ( type.IsSubclassOf( typeof(TestClassBase)) ||  type != typeof ( TestClassBase) )
        {
            System.Console.WriteLine("Success, File {0}, Line {1}", frame.GetFileName(), frame.GetFileLineNumber());
            return;
        }
    }

关于c# - 如何从 StackTrace 获取正确的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10559867/

相关文章:

winforms - Visual Studio WinForms 是否支持无窗口控件?

java - 如何获取 Java 程序特定行的堆栈跟踪

c - EDK2(UEFI 开发环境)在执行测试构建后失败

c++ - 无法在 C++ 中打印文本文件

C# 更快的堆栈跟踪

c# - 从 Sitecore 8.1 体验编辑器发布媒体项目

c# - 如何使用 .NET 6 在 Clean Architecture 中注册基础设施层依赖项?

c# - Firefox 忽略 Response.ContentType

C# 运算符重载 ==