zoukankan      html  css  js  c++  java
  • net的事件

    类或对象可以通过事件向其他类或对象通知发生的相关事情。 引发事件的类称为“发行者”,接收事件的类称为“订阅者”。
    下面实现新增一个会员时,通知AddPatientHandler类处理新增会员事件。

    .Net Framework的事件编码规范
        委托类型的名称都应该以EventHandler结束。
        委托的原型定义:有一个void返回值,并接受两个输入参数:一个Object 类型,一个 EventArgs类型(或继承自EventArgs)。
        事件的命名为 委托去掉 EventHandler之后剩余的部分。
        继承自EventArgs的类型应该以EventArgs结尾。

    第一步:发布符合 .NET Framework 准则的事件
    1.1 定义与事件一起发送自定义数据
        public class PatientEventArg : EventArgs
        {
            public int PatientId { get; set; }
            public string PatientName { get; set; }
        }

    1.2  在发布类中声明事件
         public event EventHandler<PatientEventArg> AddPatientEvent;

    1.3  在发布类引发事件

    使用受保护的虚方法来引发每个事件。 这只适用于未密封类的非静态事件,而不适用于结构、密封类或静态事件。

    遵循此准则可使派生类能够通过重写受保护的方法来处理基类事件。 受保护的 virtual方法的名称应该是为事件名加上 On 前缀而得到的名称。
     例如,名为“TimeChanged”的事件的受保护的虚方法被命名为“OnTimeChanged”。

            protected virtual void OnAddPatient(PatientEventArg e)
            {
                if (AddPatientEvent != null)
                    AddPatientEvent(this, e);
            }

    1.4 在发布类中提供对外的接口,间接引发事件

            public void AddPatient(PatientInfo patient)
            {
                OnAddPatient(new PatientEventArg { PatientId = patient.PatientID, PatientName = patient.PatientName });
            }

    第二步: 在接收事件的类定义处理事件
        public class AddPatientHandler
        {
            public void AddPatient(object sender, PatientEventArg e)
            {
                Console.WriteLine("新增一个会员:" + e.PatientName);
                Console.ReadLine();
            }
        }

    第三步:订阅事件
        public partial class _Default : System.Web.UI.Page
        {
            PatientInfo patient = new PatientInfo();
            protected void Page_Load(object sender, EventArgs e)
            {
                patient.AddPatientEvent += new AddPatientHandler().AddPatient;
            }

            protected void btaAddPatient_Click(object sender, EventArgs e)
            {
                patient.AddPatient(new PatientInfo { PatientName = "liu", PatientID = 1 });
            }
        }

  • 相关阅读:
    Blazor server VS Blazor WebAssembly
    DataTable 差集Except、交集Intersect、并集Union
    Power BI Anomaly Detection
    Power BI智能叙述
    Configure the Secure Store Service in SharePoint Server
    小批量excel数据导入oracle
    python批量写入oracle
    centos7安装java,配置的环境变量不生效 -bash: java: command not found
    nebula docker三件套组件版本问题
    shell删除指定行
  • 原文地址:https://www.cnblogs.com/50614090/p/2380673.html
Copyright © 2011-2022 走看看