//接口的声明
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);
}
}