2009-04-27 79 views
0

即使解決方案如此明顯,我應該從未發佈過這個消息,我將其作爲提醒和對其他人的參考。在虛函數中拋出異常是否是一種好的做法?

我有以下基本類:

using System; 

namespace LibraryWPF 
{ 
    public class Library 
    { 
     /// <summary> 
     /// Event fired when content is added to the libary 
     /// </summary> 
     public event EventHandler<ObjectInfoEventArgs> Library_ObjectAdded; 

     /// <summary> 
     /// Event fired when the scan of the library is finished 
     /// </summary> 
     public event EventHandler Library_Finished; 

     // Properties 

     /// <summary> 
     /// Whether to stop checking the library or not 
     /// </summary> 
     public bool Stop 
     { 
      get; 
      set; 
     } 

     /// <summary> 
     /// Where to look for content 
     /// </summary> 
     public string Root 
     { 
      get; 
      set; 
     } 

     /// <summary> 
     /// Empty instance of library's object for reflection 
     /// </summary> 
     public virtual object ObjectInfo 
     { 
      get 
      { 
       // Should this raise as exception to show if it's not been overridden? 
       return null; 
      } 
     } 

     /// <summary> 
     /// Sub class overrides this method to call it's actual find code 
     /// </summary> 
     public virtual void Find() 
     { 
      // Should this raise as exception to show if it's not been overridden? 
     } 

     /// <summary> 
     /// Build the library 
     /// </summary> 
     public void Build() 
     { 
      if (Root != null && Root.Length > 0) 
      { 
       Stop = false; 
       Find(); 
      } 

      // Final update 
      if (Library_Finished != null) 
      { 
       Library_Finished(this, null); 
      } 
     } 

     /// <summary> 
     /// Sub class calls this method to fire the ObjectAdded event 
     /// </summary> 
     /// <param name="objectInfo">Object just added to library</param> 
     protected void OnObjectAdded(object objectInfo) 
     { 
      if (Library_ObjectAdded != null) 
      { 
       Library_ObjectAdded(this, new ObjectInfoEventArgs(objectInfo)); 
      } 
     } 
    } 
} 

子類覆蓋ObjectInfo返回對象,他們正在尋找通過使用反射型的實例。他們也覆蓋Find做實際的搜索。

這樣我的應用程序代碼就可以使用基類方法,因此在編譯時它不需要知道有關子類的任何信息。我告訴它使用DI尋找什麼樣的內容。

所以 - 我的問題是這樣的:

我應該拋出一個異常在ObjectInfo基類版本和Find因此,如果子類不正確執行我得到一個運行時錯誤?或者我應該編碼ObjectInfo返回null

+0

我不能相信我完全忘了讓方法抽象化。 – ChrisF 2009-04-27 14:50:23

回答

12

如果你需要一個方法由派生類實現,爲什麼不使用抽象而不是虛擬?這將強制派生類實現該成員。如果他們不想或者不能返回一個ObjectInfo,他們可以選擇自己返回null。

+1

+1使方法抽象化。 – 2009-04-27 13:52:03

+1

謝謝 - 這就是我想到的,但不記得這個詞 - 爲什麼我不知道:) – ChrisF 2009-04-27 14:21:42

0

你當然可以這樣做,但異常通常表示執行時錯誤,而不是執行錯誤。

4

你應該聲明你的基類和被派生類實現的方法是抽象的。這完全避免了探針,因爲編譯器會檢測不覆蓋所有abstarct方法的派生類。

1

我認爲有些情況下屬性是可選的,你應該有一個屬性:ObjectInfo和一個布爾「SupportObjectInfo」。

在這種情況下,您將ObjectInfo屬性標記爲虛擬並拋出NotSupportedException。

你這樣做是因爲你的類的消費者可以測試它是否支持該屬性,並且不需要爲測試捕獲錯誤。

如果在實現中不是可選的,則應將其標記爲抽象。

1

如果您想「保護」基類的調用者接收從您的基類派生的類拋出的潛在意外異常,請考慮使用模板模式來捕獲派生類拋出的任何錯誤,並將它們轉換爲您在基類中定義的異常。您還應該考慮將派生類拋出的異常作爲內部異常傳遞。

相關問題