gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:51 24 4
gpt4 key购买 nike

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

  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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com