C#:自定义消息事件的实现

1.封装定义事件的实现

 

 //定义一个委托
public delegate void CMapLoadEventHandler(object sender, CMapLoadEventArgs e);

//暴露的外部类
public class CCallEvent
{
    //定义一个事件
    public event CMapLoadEventHandler LayerLoading;
    //LayerLoading 的响应函数,加上On是命名约定
    public void OnLayerLoading(object sender, CMapLoadEventArgs e)
    {
        if (this.LayerLoading != null)
        {
            //调用自定义事件的响应函数
            this.LayerLoading(sender, e);
        }
    }
}

 

public class CMapLoadEventArgs : EventArgs
{
    private string layerName = string.Empty;

    public CMapLoadEventArgs()
    {
    }

    public CMapLoadEventArgs(string layer_name)
    {
        this.layerName = layer_name;
    }

    public string LayerName
    {
        get { return layerName; }
        set { layerName = value; }
    }
  
}

 

 

2.自定义事件的实现

 

public partial class Form3 : Form
{

    private void button1_Click(object sender, EventArgs e)
    {
        CCallEvent callVent = new CCallEvent();
        //自定义一个事件
        callVent.LayerLoading += new CMapLoadEventHandler(mapLoad_LayerLoading);
        callVent.OnLayerLoading(this, new CMapLoadEventArgs("LayerLoading"));
    }
   //自定义事件响应函数
   private void mapLoad_LayerLoading(object sender, CMapLoadEventArgs e)
   {
       MessageBox.Show(e.LayerName);

   }

}

阅读更多
个人分类: jVC#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭