跨对象的C#事件处理程序

时间:2011-03-21 02:07:03

标签: c# events event-handling

我还在学习如何在C#中使用事件,所以我想出了一个应该是一个相当简单的练习示例。我有一个从数据库读取到List的对象。当数据库中的项目被删除时,将触发事件。如何让DBWrapper对象侦听由另一个类触发的事件?

public class DBWrapper
{
    private List<DBStruct>  _List;

    public List<DBStruct> GetList
    {
         get
         {
              return _List;
         }
    }

    void OnDeleted(object sender, EventArgs e)
    {
         //Re-read the list from db.  I could probably do
         //something with Lazy<T> loading to eliminate the event stuff
         //but that's not the point.
         _List = (from d in db select d).ToList();
    }
}

然后我有另一个带有Delete()方法的类,它触发一个事件:

public class DeleteDB
{
     public void Delete(int index)
     {
          //delete from db where d.ID = index

          //fire deletion event to a DBWrapper object
     }
}

这基本上就是我想要的输出:

void Test()
{
    DBWrapper dbw = new DBWrapper();

    Console.WriteLine(dbw.GetList);
    //Apple=1,Banana=2,Cake=3

   DeleteDB ddb = new DeleteDB();
   ddb.Delete(1);

   Console.WriteLine(dbw.GetList);
   //Banana=2,Cake=3
}

如何让一个对象侦听另一个对象触发的事件?

1 个答案:

答案 0 :(得分:0)

您将DbWrapper中的事件处理程序连接到DeleteDB上的事件。以下是使用您提供的内容解释的一些代码。

public class DeleteEventArgs:EventArgs{
    public DeleteEventArgs(int index){
        _index = index;
    }
    private readonly int _index;
    public int Index{get{return _index;}}
}

public class DeleteDB
{
     public event EventHandler<DeleteEventArgs> Deleted;

     public void Delete(int index)
     {
            if(Deleted!=null)  {
                  Deleted(this,new DeletedEventArgs(index));
            }
      }
 }

  void Test()
  {
      DBWrapper dbw = new DBWrapper();
      Console.WriteLine(dbw.GetList);
      //Apple=1,Banana=2,Cake=3

      DeleteDB ddb = new DeleteDB();
      ddb.Deleted += dbw.OnDeleted;            

      ddb.Delete(1);

      Console.WriteLine(dbw.GetList);
      //Banana=2,Cake=3
   }

请注意,OnDeleted的{​​{1}}方法需要公开才能像这样分配,除非DBWrapper方法位于Test()类内。