Ale*_*lex 7 c# events interface
我有一个定义为IStore的接口,有两种方法:
public interface IStore<TEntity>
{
TEntity Get(object identifier);
void Put(TEntity entity);
}
Run Code Online (Sandbox Code Playgroud)
我希望在Put的成功时引发一个事件(作为参考,Put可以在db中存储一行,或者在文件系统上存储文件等...)
因此,为Product类型实现Istore的类看起来有点像这样:
class MyStore : IStore<Product>
{
public Product Get(object identifier)
{
//whatever
}
public void Put(Product entity)
{
//Store the product in db
//RAISE EVENT ON SUCCESS
}
}
Run Code Online (Sandbox Code Playgroud)
我所追求的是确保IStore的每个实现都引发事件的一种方式 - 我应该使用抽象类,还是接口?
我的建议:
public abstract class Store<TEntity>
{
public abstract TEntity Get(object identifier);
public void Put(TEntity entity)
{
//Do actions before call
InternalPut(entity);
//Raise event or other postprocessing
}
protected abstract void InternalPut(TEntity entity);
}
Run Code Online (Sandbox Code Playgroud)
然后InternalPut在你的班级中覆盖