2016-07-08 1 views
4

私はtry-catch-finallyを実行しようとしています。そのため、mainLogが正常に作成されたが、その後に例外がスローされた場合、適切に破棄されるようにします。ただし、mainLogがで、が正常に作成されておらず、mainLog.Dipose()メソッド呼び出しが存在する場合は、の別の例外があります。通常、私はifステートメントを実行しますが、DocX.Create()はboolを返さないので、これを行う方法がわかりません。ありがとうございました。あなたは、デフォルトでnullmainLogを設定し、それがnullでない場合のみ、メソッドを呼び出す一般的なケースではC#最後にリソースを解放するブールなしで試してみましょう。

public static string Check_If_Main_Log_Exists_Silent() 
    { 
     DocX mainLog; 
     string fileName = DateTime.Now.ToString("MM-dd-yy") + ".docx"; 
     string filePath = @"D:\Data\Main_Logs\"; 
     string totalFilePath = filePath + fileName; 

     if (File.Exists(totalFilePath)) 
     { 
      return totalFilePath; 
     } 
     else if (Directory.Exists(filePath)) 
     { 
      try 
      { 
       mainLog = DocX.Create(totalFilePath); 
       mainLog.Save(); 
       mainLog.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("The directory exists but the log does not exist and could not be created. " + ex.Message, "Log file error"); 
       return null; 
      } 
     } 
     else 
     { 
      try 
      { 
       mainLog = DocX.Create(totalFilePath); 
       mainLog.Save(); 
       mainLog.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("The directory and log does not exist and could not be created. " + ex.Message, "Log file error"); 
       return null; 
      } 
      finally 
      { 
       if(mainLog) 
      } 
     } 

    } 
+8

'(var mainLog = DocX.Create(totalFilePath)){mainLog.Save();を使用します。 } '。 – GSerg

+0

あなたはコードを試してみることを単純化するべきです - メッセージの一時変数を使用してください。 –

答えて

6

using statementを追加すると、コードブロックの最後にnullがある場合にのみdisposeが呼び出されます。それはそれらの便利な統語的糖の一つです。

4

。オブジェクトがIDisposableインタフェースを実装する場合は、usingを使用してGaspa79の答えが示すように、最も簡単な方法です

if (mainLog != null) 
    mainLog.Dispose(); 

:場合は、古いバージョンの単純なために

mainLog?.Dispose(); 

:C#6を使用すると、便利なフォームを使用することができます。

関連する問題