dimanche 21 février 2021

How to subscribe a void method with no parameters to a static event(Action) that is in different class at runtime using Reflection in C#

So far I have been able to add any method that matches this signature (Action<ILoginSession>)successfully in the IsLoginCallback(MethodInfo method) method. But I tried using var runtimeDelegate = (Action)method.CreateDelegate(typeof(Action), null); with a null because the class is static but I keep getting an error. Is it possible to subscribe a void method with no parameters at runtime to an static event Action with no parameters? I have found similar questions but they used an instance of a class to get the static event but in my case the class is also static so I can't the type for a proper reference. Any help is appreciated thanks!

    public static void AddLoginRuntimeCallbackMethods()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();

        foreach (var type in assembly.GetTypes())
        {
            foreach (var method in type.GetMethods(BindingFlags.NonPublic |
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
            {
                if (method.ReflectedType.IsSubclassOf(typeof(VivoxManager))) continue;

                if (Attribute.IsDefined(method, typeof(LoginCallbackAttribute), false))
                {
                    if (IsLoginCallback(method)) continue;
                }
            }
        }
    }

    public static bool IsLoginCallback(MethodInfo method)
    {
        var runtimeDelegate = (Action<ILoginSession>)method.CreateDelegate(typeof(Action<ILoginSession>), null);
        if(method.GetCustomAttribute<LoginCallbackAttribute>(false) != null)
        {
            switch (method.GetCustomAttribute<LoginCallbackAttribute>(false).action)
            {
                case LoginAction.LogginIn:
                    VivoxLogin.VivoxLoggingIn += runtimeDelegate;
                    return true;
                case LoginAction.LoggedIn:
                    VivoxLogin.VivoxLoggedIn += runtimeDelegate;
                    return true;
                case LoginAction.LoggingOut:
                    VivoxLogin.VivoxLoggingOut += runtimeDelegate;
                    return true;
                case LoginAction.LoggedOut:
                    VivoxLogin.VivoxLoggedOut += runtimeDelegate;
                    return true;
            }
        }
        return false;
    }




Aucun commentaire:

Enregistrer un commentaire