src/ShenNius.Share.Infrastructure/EventBus/EventBus.cs
(开头部分) 4KB这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。
/*************************************
* 类名:EventBus
* 作者:realyrare
* 邮箱:mhg215@yeah.net
* 时间:2021/8/3 19:53:49
*┌───────────────────────────────────┐
*│ 版权所有:神牛软件 │
*└───────────────────────────────────┘
**************************************/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
namespace ShenNius.Share.Infrastructure.EventBus
{
public class EventBus
{
public static EventBus Default => new EventBus();
/// <summary>
/// 定义线程安全集合
/// </summary>
private readonly ConcurrentDictionary<Type, List<Type>> _eventAndHandlerMapping;
public EventBus()
{
_eventAndHandlerMapping = new ConcurrentDictionary<Type, List<Type>>();
MapEventToHandler();
}
/// <summary>
///通过反射,将事件源与事件处理绑定
/// </summary>
private void MapEventToHandler()
{
Assembly assembly = Assembly.GetEntryAssembly();
foreach (var type in assembly.GetTypes())
{
if (typeof(IEventHandler).IsAssignableFrom(type))//判断当前类型是否实现了IEventHandler接口
{
Type handlerInterface = type.GetInterface("IEventHandler`1");//获取该类实现的泛型接口
if (handlerInterface != null)
{
Type eventDataType = handlerInterface.GetGenericArguments()[0]; // 获取泛型接口指定的参数类型
if (_eventAndHandlerMapping.ContainsKey(eventDataType))
{
List<Type> handlerTypes = _eventAndHandlerMapping[eventDataType];
handlerTypes.Add(type);
_eventAndHandlerMapping[eventDataType] = handlerTypes;
}
else
{
var handlerTypes = new List<Type> { type };
_eventAndHandlerMapping[eventDataType] = handlerTypes;
}
}
}
后面还有 57 行代码,解锁后查看完整代码
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
