我在基类中实现了一个类似的模式,我是这样做的:
底座:
public virtual void OnBeforeSavingRecord(object sender, EntitySavingEventArgs<T> e)
{ }
在派生类中,我正好有您使用的调用:
派生:
public override void OnBeforeSavingRecord(object sender, EntitySavingEventArgs<Bank> e)
{
//Do something with entity item before saving
base.OnBeforeSavingRecord(sender, e);
}
就我的情况来说,只要打电话就可以了
OnBeforeSavingRecord(this, new EntitySavingEventArgs<T>() { SavedEntity = item });
整个场景对我来说都很管用。
编辑:
使命感
OnBeforeSavingRecord
如果从派生类的实例调用它,将在派生类的重写方法中执行代码!
如果我没弄错的话,你想在方法中触发事件
Create
但希望执行派生类的事件代码。如果事件像您的情况一样被重写,则会发生这种情况。您可以使用这个简单的Console应用程序测试它:(只需复制粘贴并运行)
public class Service
{
public virtual event System.EventHandler<EventArgs> BeforeSavingRecord;
public virtual void OnBeforeSavingRecord(object sender, EventArgs e)
{
Console.WriteLine("Base: OnBeforeSavingRecord method call");
}
public virtual void Create(object item)
{
Console.WriteLine("Base: Create method call");
// this will call the method of the derived class! if you call it from an instance of the derived class
OnBeforeSavingRecord(this, new EventArgs());
}
}
public partial class BankBusiness : Service
{
public override void OnBeforeSavingRecord(object sender, EventArgs e)
{
//Do something with entity item before saving
Console.WriteLine("Derived Class OnBeforeSavingRecord CALL");
base.OnBeforeSavingRecord(sender, e);
}
}
static void Main(string[] args)
{
BankBusiness bankBiz = new BankBusiness();
bankBiz.Create(new object());
Console.ReadKey();
}