2011-11-11 13 views
3

下記のコードから次のエラーが表示され、オブジェクトを適切にキャストする方法が見つかりません。どんな助けでも大歓迎です。C#変換エラー

エラーは、ex = e.ExceptionObjectで発生します。ライン。

'オブジェクト'を暗黙的に '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(); 
    } 
} 

答えて

2
Exception ex = (Exception)e.ExceptionObject; 
+1

ありがとうUwe。私はVB.Netのプログラマーなので、C#の厳しいタイプには慣れていませんが、今すぐ取得しています。再度、感謝します! –

1

あなたがする必要があります明示的にキャスト:(Exception) e.ExceptionObjectあなたは例外のある種期待されている条件があるかもしれません:

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

などなどを。

0

this StackOverflow questionで説明されている理由により、UnhandledExceptionEventArgs.ExceptionObjectは、ではなく、objectと静的に型指定されています。したがって、それをExceptionとして扱いたい場合は、キャストする必要があります。

ここでの回答の1つとして、通常はキャスト(つまり、(Exception)でキャスト)が可能な場合があります。