C# 如何仅从UnhandledException获取消息?

C# 如何仅从UnhandledException获取消息?,c#,C#,我使用的是AppDomain提供的UnhandledException,我所做的基本上是: static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; } static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {

我使用的是
AppDomain
提供的
UnhandledException
,我所做的基本上是:

static void Main(string[] args)
{
        AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
}

static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
   e.ExceptionObject.Message? <- there is no message
   Console.WriteLine(e.ExceptionObject.ToString());
   Console.WriteLine("Press a key for exit.");
   Console.ReadLine();
   Environment.Exit(1);
}
static void Main(字符串[]args)
{
AppDomain.CurrentDomain.UnhandledException+=UnhandledExceptionTrapper;
}
静态void UnhandledExceptionTrapper(对象发送器,UnhandledExceptionEventArgs e)
{
e、 ExceptionObject.Message?问题在于它是一个对象。您可以将其强制转换为Exception以获取

或者MSDN建议这样做

Exception exception = (Exception) e.ExceptionObject;
var message = exception.Message;

也许
如果(e.ExceptionObject是Exception){((Exception)e.ExceptionObject).Message;}
啊,所以我需要强制转换它,让我试试。谢谢你的提示!永远,永远,永远不要这样做。只有e.ExceptionObject.ToString()产生一个合理的诊断,不会让(比如)一个InnerException掉到地板上。@HansPassant我知道这一点,我只是在学习
AppDomain
如何在整个应用程序中引发异常。@Rahul是的,第一个使用
as
仅当
ExceptionObject
是一个异常时才执行强制转换。似乎工作正常,谢谢!a如果我这样做,就会出现奇怪的情况。
Console.WriteLine(“Message:+Message”);
消息没有打印。相反,这项工作:
Console.WriteLine(Message);
Exception exception = (Exception) e.ExceptionObject;
var message = exception.Message;