我从下面显示的代码中得到以下错误,但无法找到正确转换对象的方法。非常感谢任何帮助。
ex = e.ExceptionObject发生错误;线。
无法将类型'object'隐式转换为'System.Exception'。一个 存在显式转换(您是否错过了演员?)(CS0266) - C:\ DocmentMDB \ DocumentMDB.ConvertedToC#\ ErrorHandler.cs:59.9
public static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
// handles all unhandled (i.e. no Catch block) exceptions
// the following code must be placed in Sub Main and the project
// use Sub Main as startup
//Dim currentDomain As AppDomain = AppDomain.CurrentDomain
//AddHandler currentDomain.UnhandledException, AddressOf myExceptionHandler
Exception ex = null;
ex = e.ExceptionObject;
string strErrorMsg = null;
string strDisplayMsg = null;
string strPrintMsg = null;
int intLoc = 0;
strErrorMsg = "Unhandled Error In : " + strFormName + " - " + ex.TargetSite.Name + Constants.vbCrLf + Constants.vbCrLf + ex.Message;
strPrintMsg = "Error detected: " + DateAndTime.Now + Constants.vbCrLf + Constants.vbCrLf + strErrorMsg + Constants.vbCrLf + Constants.vbCrLf + ex.StackTrace;
strDisplayMsg = "Report this error to your System Administrator" + Constants.vbCrLf + Constants.vbCrLf + strErrorMsg + Constants.vbCrLf + Constants.vbCrLf + "Click YES to print this message.";
if (MessageBox.Show(strDisplayMsg, "Unhandled Program Error", MessageBoxButtons.YesNo) == DialogResult.Yes) {
// print the error message
ErrPrint myPrintObject = new ErrPrint(strPrintMsg);
myPrintObject.Print();
}
}
答案 0 :(得分:2)
Exception ex = (Exception)e.ExceptionObject;
答案 1 :(得分:1)
您需要明确地投射它:(Exception) e.ExceptionObject
可能存在您期望某种异常的条件:
if (e.ExceptionObject is InvalidOperationException)
{
// ...
}
等等。
答案 2 :(得分:0)
出于this StackOverflow question中讨论的原因,UnhandledExceptionEventArgs.ExceptionObject
被静态输入为object
,而不是Exception
。因此,如果您想将其视为Exception
,则必须进行投射。
请注意,根据其中一个答案,通常情况下您可以安全地直接演员(即使用(Exception)
演员)。