Circular Dependency in Two Projects in C#

后端 未结 4 1315
轻奢々
轻奢々 2020-12-20 12:42

I have two projects in a solution named ProjectA (ConsoleApplication) and ProjectB (ClassLibrary). ProjectA has a reference to ProjectB. Generally speaking, ProjectA calls a

4条回答
  •  渐次进展
    2020-12-20 12:51

    I would actually create your own event on ClassB

    public event EventHandler MySpecialHook;
    

    EventHandler is a standard delegate of

    public delegate void EventHandler(object sender, EventArgs e);
    

    Then, in your Class A, after creating your instance of ClassB, hook into the event handler for notification when something occurs in B that A should know about. Much like an OnActivated, OnLostFocus, OnMouseMove or similar events (but they have delegate different signatures)

    public class ClassB {
    
    public event EventHandler MySpecialHook;
    
    public void SomeMethodDoingActionInB()
    {
    
        // do whatever you need to.
        // THEN, if anyone is listening (via the class A sample below)
        // broadcast to anyone listening that this thing was done and 
        // they can then grab / do whatever with results or any other 
        // properties from this class as needed.
        if( MySpecialHook != null )
            MySpecialHook( this, null );
     } 
    }
    
    public class YourClassA
    {
    
       ClassB YourObjectToB;
    
       public YourClassA
       {
          // create your class
          YourObjectToB = new ClassB();
          // tell Class B to call your "NotificationFromClassB" method
          // when such event requires it
          YourObjectToB += NotificationFromClassB;
       }
    
       public void NotificationFromClassB( object sender, EventArgs e )
       {
          // Your ClassB did something that your "A" class needs to work on / with.
          // the "sender" object parameter IS your ClassB that broadcast the notification.
       }
    }
    

提交回复
热议问题