C#构造函数事件 [英] C# constructor event

查看:158
本文介绍了C#构造函数事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,当我通过form创建一个雇员对象时,我想给出一条消息;

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 ctorDel(); 

class Employee
{
    private int empID;
    private string empName;

    public event ctorDel myEvent;

    public Employee(int empID,string empName)
    {
        this.empID = empID;
        this.empName = empName;

        **if (myEvent != null)
        {
            myEvent();
        }**
    }

和形式

  int id = Convert.ToInt16(textBox1.Text);
            string name = textBox2.Text;

            Employee emp = new Employee(id, name);
            emp.myEvent += new ctorDel(showMessage);

和功能

 public void showMessage()
        {
            MessageBox.Show("An employee is created");
        }

推荐答案

您要完成什么?您尝试的方法不起作用的原因是因为您将委托附加到ctor之后.一旦您致电新员工",该事件就早已被解雇.

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.

这篇关于C#构造函数事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆