c#事件 的三种使用方式

 

    1. 使用delegate 关键字定义事件的委托
       public delegate void Notify();
      public event Notify ProcessCompeleted;

      public class EventSample
      {
      public delegate void Notify();

      public event Notify ProcessCompeleted;

      public void Start()
      {
      Console.WriteLine("开始作业");
      //业务逻辑

      //处理完毕后触发事件
      OnProcessCompeleted();
      }

      protected virtual void OnProcessCompeleted()
      {
      ProcessCompeleted?.Invoke();
      //判断是否订阅了
      //if (ProcessCompeleted != null)
      // ProcessCompeleted();
      }
      }

      class Program
      {
      static void Main(string[] args)
      {
      EventSample sample = new EventSample();
      sample.ProcessCompeleted += Sample_ProcessCompeleted;
      sample.Start();

      Console.ReadLine();
      }

      private static void Sample_ProcessCompeleted()
      {
      Console.WriteLine("处理完成");
      }
      }
      ————————————————
      版权声明:本文为CSDN博主「一个有料的码农」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
      原文链接:https://blog.csdn.net/sud423/article/details/123848092

internal class Program
{
static void Main(string[] args)
{
fabu f = new fabu();
dingyue dy = new dingyue();
f.tEvent += dy.SendMessage;
f.chufa();
Console.ReadLine();
}
}

public class fabu
{

// public delegate void EventHandler(object sender, EventArgs e);
public event EventHandler tEvent;
// 事件的触发函数
public void chufa() {

tEvent(this, null);
}

}

public class dingyue
{
public void SendMessage(Object sender,EventArgs e)
{

Console.WriteLine("订阅了事件");
}


}
}

 

自定义事件 自定义事件继承 EventArgs方便数据传递 在自定义事件中定义需要传递的数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestEventArgs
{


public class TestEvent : EventArgs
{
public int count { set; get; }

}
//事件发布者
public class CountArgs
{
public event EventHandler<TestEvent> CountDo;
//触发事件
public void DoCount()
{
TestEvent te = new TestEvent();
for (int i = 0; i < 10; i++)
{
if(i%5 ==0)
{
te.count += i;
CountDo(this,te);
}

}
}


}
//事件的订阅者
public class Coun {
public int count;
public void Count(Object sender, TestEvent e)
{
count = e.count;
Console.WriteLine(count);

}
}
public class Program_ {

static void Main() {

CountArgs ca = new CountArgs();
Coun coun = new Coun();
ca.CountDo += coun.Count;
ca.DoCount(); // 触发事件
Console.ReadLine();
}
}


}

posted @ 2022-10-31 21:27  我是锤子  阅读(257)  评论(0编辑  收藏  举报