c# - 在 Debug.Assert 语句中插入行号

标签 c# .net debugging

我们使用 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.

示例:

alt text

如果您在断言对话框中没有看到文件名或行号,那么 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/

相关文章:

c# - Silverlight - 通过 C# 将文本添加到 Bing map 中的图钉

c# - UWP 应用程序和 .NET Core RC2 : cannot reference netstandard1. 4 个包

c# - 意外的子类型 : MyNamespace. MyInheritedClass

c# - 行首的正则表达式 - 或 - 句子中的最后一个数字

c# - 在自定义控件中处理来自 DataTemplate 的事件

c# - 从 .NET 设置系统时区

.net - 在 ASP.NET RegularExpressionValidator 中使正则表达式不区分大小写

c++ - 用于非托管 C++ 代码的调试器可视化工具?

android - 如何调试 Android Native 崩溃日志(可能是多个 webview 问题)?

ios - 当我在调试中放置它时,Xcode 8 不显示任何变量值