C# constructor event

后端 未结 6 821
南旧
南旧 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:16

    What is it you're trying to accomplish? The reason what you've tried doesn't work is because you're attaching your delegate after the ctor. Once you've called "new Employee" the event is long since fired.

    If you really need such an event, create a factory class:

    public delegate void EmpCreated();
    public EmployeeFactory {
      public event EmpCreated myEvent;
      public Employee Create(int empId, string empName){
        var result = new Employee(empId, empName);
        if(myEvent != null) myEvent();
        return result;
      }
    }
    

    Subscribe to the event on the factory class and you'll get the event.

提交回复
热议问题