c# 创建委托 消息订阅_C#/Java 使用接口实现委托和事件订阅

本文介绍了如何在C#中通过定义接口来创建委托和实现事件订阅。通过一个`EventMgr`类管理订阅者列表,事件触发时会调用所有订阅者的`CustomState`方法。示例中,`AClass`和`BClass`实现了`ICustomInterface`接口,并在`Main`函数中订阅事件,当`EventTrigger`被调用时,两个类会接收到并处理事件。
摘要由CSDN通过智能技术生成

//接口的声明

public interface ICustomInterface

{

void CustomState(CustomEventArgs e);

}

//订阅管理类

public class EventMgr

{

public static List customInterfaces = new List();

//事件订阅

public static void AddListener(ICustomInterface c)

{

customInterfaces.Add(c);

}

//事件移除

public static void RemoveListener(ICustomInterface c)

{

if (customInterfaces.Contains(c))

customInterfaces.Remove(c);

}

//事件触发

public static void EventTrigger(CustomEventArgs e)

{

for (int i = 0; i < customInterfaces.Count; i++)

{

customInterfaces[i].CustomState(e);

}

}

}

//这个是事件参数类,里面含有一些传递的参数

public class CustomEventArgs

{

public string name;

//添加一个构造函数

public CustomEventArgs(string name)

{

this.name = name;

}

}

class Program

{

static void Main(string[] args)

{

//把实现了接口的类声明为接口类型

ICustomInterface aClass = new AClass();

ICustomInterface bClass = new BClass();

//把AClass和BClass添加到订阅

EventMgr.AddListener(aClass);

EventMgr.AddListener(bClass);

//触发事件

EventMgr.EventTrigger(new CustomEventArgs("事件参数"));

Console.ReadKey();

}

}

//这个是接受事件的类,需要实现该接口

public class AClass : ICustomInterface

{

//接收到事件则打印

public void CustomState(CustomEventArgs e)

{

Console.WriteLine("A收到事件 "+ e.name);

}

}

//这个是接受事件的类,需要实现该接口

public class BClass : ICustomInterface

{

//接收到事件则打印

public void CustomState(CustomEventArgs e)

{

Console.WriteLine("B收到事件" + e.name);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值