我们使用 Debug.Assert
向开发人员发出代码中的问题信号。我想在发生错误的地方添加行号,但不要对其进行硬编码,因为这可能会改变,我们会忘记更新字符串。
添加错误的行号会很方便。有什么想法吗?
最佳答案
默认情况下,Debug.Assert
已经包含堆栈跟踪信息:
When the application runs in user-interface mode, it displays a message box that shows the call stack with file and line numbers.
示例:
如果您在断言对话框中没有看到文件名或行号,那么 PDB 文件(作为编译的一部分生成)丢失或无法访问。 PDB 文件包含文件和线路调试信息。
在 C# 中没有与 C/C++ 的 __FILE__
和 __LINE__
魔法宏真正等价的东西,但是如果你仍然想要断言对话框之外的这些信息,你可以使用StackTrace
类得到它。这要求您有可用的调试信息(上面提到的 PDB 文件)。由于您可能将其用于开发,因此这是一项安全要求。
using System.Diagnostics;
namespace Managed
{
class Program
{
static void Main(string[] args)
{
AssertWithCallSite(false, "Failed!");
}
[Conditional("DEBUG")]
static void AssertWithCallSite(bool condition, string message)
{
if (!condition)
{
var callSite = (new StackTrace(1, true)).GetFrame(0);
string fileName = callSite.GetFileName();
int lineNumber = callSite.GetFileLineNumber();
string assertMessage = string.Format(
"Assert at {0}:{1}:\n{2}",
fileName,
lineNumber,
message
);
Debug.Assert(false, assertMessage);
}
}
}
}
关于c# - 在 Debug.Assert 语句中插入行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3868644/