即使解決方案如此明顯,我應該從未發佈過這個消息,我將其作爲提醒和對其他人的參考。在虛函數中拋出異常是否是一種好的做法?
我有以下基本類:
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
?
我不能相信我完全忘了讓方法抽象化。 – ChrisF 2009-04-27 14:50:23