C# constructor event

后端 未结 6 772
南旧
南旧 2021-01-21 03:53

i created a class and when i create an employee object via form , i want to give a message;

this is my class, event and delegate

public delegate void cto         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 04:33

    By the time you subscribe for this event the instance is already constructed. I would recommend using Factory pattern to hide the constructor.

    class EmployeeFactory
    {
         public Employee Create(int id, string name)
         {
             Employee instance = new Employee(id, name);
    
             var handler = EmployeeCreated;
             if (handler != null)
             {
                  EmployeeEventArgs e = new EmployeeEventArgs(instance);
                  handler(e);    
             }
    
             return instance;
         }
    
         public event EventHandler  EmployeeCreated;
    }
    

    Event subscription:

      factory.EmployeeCreated += MyHandler;
    

    Instance construction:

      var emp = factory.Create(id, name);  
    

提交回复
热议问题