开发者

C# Event Handler Across Objects

I'm still learning how to use Events in C# so I've come up with what should be a fairly simple practice example. I have an object that reads from a database into a List. When an item in the database gets deleted an event is triggered. How do I have a DBWrapper object listen for an event triggered by another class?

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();开发者_运维技巧
    }
}

I then have another class with a Delete() method that triggers an event:

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

          //fire deletion event to a DBWrapper object
     }
}

This is essentially what I want my output to be:

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
}

How do I have one object listen to an event triggered by another object?


You wire up the event handler in the DbWrapper to the event on the DeleteDB. Here is some code to explain, using what you provided.

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
   }

Please note that your OnDeleted method of the DBWrapper would need to made public to assign it like this, unless the Test() method is inside of the DBWrapper class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜