即使解决方案如此明显,我也不应该发布这个,我将其作为提醒和其他人的有用参考点.
我有以下基类:
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));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
子类重写ObjectInfo以返回他们正在寻找反射使用的对象类型的实例.他们还覆盖Find了进行实际搜索.
这样我的应用程序代码就可以使用基类方法,因此它不必在编译时知道有关子类的任何信息.我告诉它使用DI寻找什么样的内容.
所以 - 我的问题是:
我应该在的基类版本抛出一个异常ObjectInfo,并Find因此,如果子类不正确执行我得到一个运行时错误?或者我应该编码ObjectInfo返回null?