【发布时间】:2017-02-06 07:36:56
【问题描述】:
我想在派生类中重写基类方法,然后在派生类中做一些事情。因此基类方法使用其泛型类型调用。然后我的目标是触发被覆盖的派生类方法。
我有以下代码:
public class Service<T> : Interface.IService<T> where T : class
{
public virtual event System.EventHandler<EntitySavingEventArgs<T>> BeforeSavingRecord;
public Service()
{
}
public virtual void OnBeforeSavingRecord(object sender, EntitySavingEventArgs<T> e)
{
}
private readonly DbContext _dbContext;
public Service(DbContext dbContext)
{
_dbContext = dbContext;
}
public virtual void Create(T item)
{
if (item == null)
throw new ArgumentNullException("item");
BeforeSavingRecord?.Invoke(this, new EntitySavingEventArgs<T>() { SavedEntity = item });
_dbContext.Set(typeof(T)).Add(item);
_dbContext.SaveChanges();
}
}
在它的派生类中我有这样的东西:
[Service]
public partial class BankBusiness : Service<Bank>, IBankBusiness
{
public BankBusiness()
: base(ContainerManager.Container.Resolve<MyContext>())
{
}
public override void OnBeforeSavingRecord(object sender, EntitySavingEventArgs<Bank> e)
{
//Do something with entity item before saving
base.OnBeforeSavingRecord(sender, e);
}
}
然后在我调用时在我的控制器中
bankBiz.Create(new Bank() { ... });
我想触发注册到 BeforeSavingRecord 事件的 bankBiz(派生类)重写方法 (OnBeforeSavingRecord)。
我不知道我的方案是否正确,以及我如何才能触发它。
如果不正确,我应该怎么做。
【问题讨论】:
-
这行:
BeforeSavingRecord?.Invoke(this, new EntitySavingEventArgs<T>() { SavedEntity = item });不会导致事件触发吗? -
确实如此。但我不想在派生类中调用它。我想通过覆盖做一些事情,调用被覆盖的方法。
-
那我真的不明白你。你写道:“然后我的目标是触发被覆盖的派生类方法。”我在您发布的代码中看到的唯一被覆盖的方法是
public override void OnBeforeSavingRecord。 -
在方法
Create中调用OnBeforeSavingRecord如果您从派生类的实例调用它,将首先执行派生类的重写方法中的代码。请查看我的 edfit -
谢谢伙计。您的解决方案有效,但在我的情况下无效。请查看我的上一篇文章
标签: c# event-handling overriding