什么是Exception的.ToString()和.Message之间的区别?

Bra*_*118 21 c# exception

我正在查看一些代码,我发现了e.ToString(),我想知道使用ToString()方法而不是.Message是否有区别?

阅读下面,听起来它返回更多信息.

来自微软的文档

.NET Compact Framework支持的ToString.覆盖.创建并返回当前异常的字符串表示形式.

.NET Compact Framework支持的消息.获取描述当前异常的消息.

Gra*_*ICA 20

如果您希望一次性获取尽可能多的信息,请致电ToString():

ToString的默认实现获取抛出当前异常的类的名称,消息 (我的重点),在内部异常上调用ToString的结果,以及调用Environment.StackTrace的结果.如果这些成员中的任何一个为Nothing,则其值不包含在返回的字符串中.

方便的是你不必自己将所有单个元素附加在一起,检查以确保没有空元素等等.它都是内置的......

Exception.ToString方法

您还可以在reference.microsoft.com上查看实际的源代码.


Ian*_*son 12

尝试使用.NET Reflector或类似的东西来查看System.Exception上的ToString方法正在做什么:

[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
    return this.ToString(true);
}

private string ToString(bool needFileLineInfo)
{
    string className;
    string message = this.Message;
    if ((message == null) || (message.Length <= 0))
    {
        className = this.GetClassName();
    }
    else
    {
        className = this.GetClassName() + ": " + message;
    }
    if (this._innerException != null)
    {
        className = className + " ---> " + this._innerException.ToString(needFileLineInfo) + Environment.NewLine + "   " + Environment.GetRuntimeResourceString("Exception_EndOfInnerExceptionStack");
    }
    string stackTrace = this.GetStackTrace(needFileLineInfo);
    if (stackTrace != null)
    {
        className = className + Environment.NewLine + stackTrace;
    }
    return className;
}
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 8

ToString()Message随着回归StackTrace.
ToString()也将递归地包括InnerExceptions.

ToString()返回一个更长的字符串,这比Message跟踪错误时更有用.