创建委托反射

时间:2018-11-04 11:03:26

标签: c# .net unity3d

我有一个事件总线设置(使用Redbus)来处理游戏中的事件。我想拥有一个自动将功能注册到事件总线的属性。

我通常会注册一个事件,例如:

public void RegisterEvents()
{
    EVENT_BUS.Subscribe<InitializationEvent>(this.OnInit);
}

public void OnInit(InitializationEvent e)
{
}

但我最好还是做

[EventHandler]
public void OnInit(InitializationEvent e)
{
}

我有代码可以遍历我的类和方法,以获取具有EventHandler属性的每个方法,但是当我尝试创建委托以向事件总线注册时,会出现此错误

ArgumentException: method arguments are incompatible

这是我的代码:

private void SetupEventHandlers()
    {
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (var _class in assembly.GetTypes())
            {
                if (!_class.IsClass)
                    continue;

                foreach (var method in _class.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
                {
                    if (!method.IsDefined(typeof(EventHandler), false))
                        continue;

                    if (method.IsStatic)
                    {
                        Debug.LogError("Cannot use EventHandler attribute on static fields");
                        continue;
                    }

                    var parameters = method.GetParameters();
                    var eventType = parameters[0].ParameterType;

                    var a = Activator.CreateInstance(_class);

                    var d = Delegate.CreateDelegate(Expression.GetActionType(method.GetType()), a, method);

                    //do rest of registration stuff
                }
            }
        }
    }

有人对如何使它起作用有任何建议吗?

1 个答案:

答案 0 :(得分:0)

我想[EventHandler]引用一个EventHandlerAtttribute类。 然后method.IsDefined(typeof(EventHandler),false)也应该是method.IsDefined(typeof(EventHandlerAtttribute),false)。