如何在 C# 中控制 "Exception Thrown" window 中显示的消息?

How do I control the message shown in the "Exception Thrown" window in C#?

我有一个派生自 System.Exception 的自定义异常类型,称为 ErrorCodeException。它有一个 "ErrorCode" 属性,我想在调试时显示它。问题是,window 只显示基本类型的 "Message" 属性。

目标是显示此 ToString() 函数的 return 值:

public override string ToString()
{
   return $"Error code: {(int)ErrorCode} - {ErrorCode.ToString()} Message: {Message}";
}

我的自定义异常类型的完整声明:

[System.Diagnostics.DebuggerDisplay("{ToString()}")]
public class ErrorCodeException : Exception
{
    public ErrorCode ErrorCode { get; private set; }

    public ErrorCodeException(ErrorCode errorCode, string message) : base(message)
    {
        this.ErrorCode = errorCode;
    }

    public ErrorCodeException(ErrorCode errorCode) : base()
    {
        this.ErrorCode = errorCode;
    }

    public override string ToString()
    {
        return $"Error code: {(int)ErrorCode} - {ErrorCode.ToString()} Message: {Message}";
    }
}

实施 ToString() 解决了这个问题,因为它会显示在调试控制台中的复杂对象上。