【问题标题】:C# conversion errorC# 转换错误
【发布时间】:2011-12-27 02:58:11
【问题描述】:

我从下面显示的代码中收到以下错误,并且找不到正确投射对象的方法。非常感谢任何帮助。

错误发生在 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();
    }
}

【问题讨论】:

    标签: c#


    【解决方案1】:
    Exception ex = (Exception)e.ExceptionObject;
    

    【讨论】:

    • 谢谢你。由于我是 VB.Net 程序员,我不习惯 C# 的严格类型,但我现在明白了。再次感谢!
    【解决方案2】:

    您需要显式转换:(Exception) e.ExceptionObject 在某些情况下您可能会期待某种异常:

    if (e.ExceptionObject is InvalidOperationException)
    {
        // ...
    }
    

    等等。

    【讨论】:

      【解决方案3】:

      由于this StackOverflow question 中讨论的原因,UnhandledExceptionEventArgs.ExceptionObject 静态类型为object,而不是Exception。因此,如果您想将其视为Exception,则必须进行转换。

      请注意,根据那里的答案之一,通常情况下您可以安全地直接投射(即,使用(Exception) 投射)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多