C#事件

c#事件
一:为什么使用事件
事件对应着订阅和发布,订阅事件的对象会在事件发布时直接收到通知,执行方法。
二:事件的使用
public event 委托名 事件名;
事件的订阅:
事件名+=方法名;这个方法名一定对应着委托的相同参数和返回值

另外的一种方式是:通过继承EventArgs方式去实现的

委托的参数里面必须是(object sender, EventArgs的子类 e)


using System;
using System.Collections.Generic;
using System.Diagnostics;

//玩游戏的时候 小明 小红 和小丑 加油
namespace MyEvent
{
internal class Program
{
public static void Main(string[] args)
{
Friend f1 = new Friend("小明");
Friend f2 = new Friend("小红");
GameProgress gameValue = new GameProgress();
gameValue.NoticeEvent += new GameProgress.NoticeHandel(f1.Fighting); //绑定事件
gameValue.NoticeEvent += showFriendInfo; //绑定事件 可以不需要委托
gameValue.NoticeEvent2 += new GameProgress.NoticeHandel2(f2.Fighting); //绑定事件

for (int i = 0; i <= 100; i++)
{
if (i >= 98)
{
gameValue.OnNoticeEvent("KanekiKen", i);
}
}
}

public static void showFriendInfo(string name, int value)
{
Console.WriteLine("name = {0} , value = {1}", name, value);
}
}


//第二种方式是通过继承EventArgs方式去实现的
public class NoticeEventArgs : EventArgs
{
public string Name { get; }
public int Value { get; }

public NoticeEventArgs(string name, int value)
{
this.Name = name;
this.Value = value;
}
}

public class GameProgress
{
public int Progress { get; set; } = 0;

public delegate void NoticeHandel(string name, int value); //第一种的方法的委托

public delegate void NoticeHandel2(object sender, NoticeEventArgs e); //第二种的方法的委托

public event NoticeHandel NoticeEvent; //第一种事件的委托
public event NoticeHandel2 NoticeEvent2; //第二种事件的委托

//通知事件
public virtual void OnNoticeEvent(string name, int value)
{
NoticeEvent?.Invoke(name, value); //第一个事件的调用
NoticeEvent2?.Invoke(this, new NoticeEventArgs(name, value)); //第二个事件的调用
}
}

class Friend
{
public string Name { get; }

public Friend(string name)
{
this.Name = name;
}

//和第一种委托匹配的参数
public void Fighting(string name, int value)
{
Console.WriteLine("{0}::{1},加油。。现在已经完成了{2}", Name, name, value);
}

//和第二种委托匹配的参数
public void Fighting(object sender, NoticeEventArgs e)
{
Console.WriteLine("{0}::{1},加油。。现在已经完成了{2}", Name, e.Name, e.Value);
}
}
}
原文地址:https://www.cnblogs.com/kanekiken/p/7561057.html