如何使用反射订阅事件。 C#

时间:2018-05-24 21:10:15

标签: c# events reflection

我似乎无法弄清楚为什么这会抛出“无法绑定到目标方法,因为它的签名或安全透明性与委托类型的不兼容。”具体来说,这部分method.CreateDelegate(eventInfos[0].EventHandlerType, new Commands());

//These are defined at the top of the class
public delegate Task MessageReceivedAsyncDelegate(SocketMessage arg);
public delegate void MessageReceivedDelegate(SocketMessage arg);
public event MessageReceivedAsyncDelegate MessageReceivedCommandAsync;
public event MessageReceivedDelegate MessageReceivedCommand;
//These are defined at the top of the class


    Type B = typeof(Base);
    Type C = typeof(Commands);
    MethodInfo[] methods = C.GetMethods();
    foreach (MethodInfo method in methods)
    {
        EventInfo[] eventInfos = B.GetEvents();
        if(method.GetCustomAttributes(typeof(SubscribeToMessageRecivedAttribute)).Any()
        {
            if (method.ReturnType == typeof(Task))
            {
                try { eventInfos[0].AddEventHandler(C, method.CreateDelegate(eventInfos[0].EventHandlerType, new Commands())); }
                catch(Exception exception) { Console.WriteLine(exception); }
            }
            else eventInfos[1].AddEventHandler(C, method.CreateDelegate(eventInfos[1].EventHandlerType, new Commands()));
        }
    }

它试图添加的方法

  public partial class Commands : ModuleBase<SocketCommandContext>
    {
        [SubscribeToMessageRecived]
        public static async Task Mock(SocketMessage arg)
        {
            Console.WriteLine("Mocking");
            if (Base.mockList.Contains((int)arg.Author.Id))
            {
                char[] msgArray = arg.Content.ToCharArray();
                for (int i = 0; i < arg.Content.Length; i++)
                {
                    if (DaMef.RandomRange(0,3) == 1) msgArray[i] = msgArray[i].ToString().ToLower().ToCharArray()[0];
                    else msgArray[i] = msgArray[i].ToString().ToUpper().ToCharArray()[0];
                }

            string finalString = msgArray.ToString();
            await arg.Channel.SendMessageAsync(finalString + "\nhttps://imgur.com/a/HsiBmYc");
            }
        }
    }

我正在尝试使用“SubscribeToMessageRecivedAttribute”将命令中的所有方法订阅到事件。

网上有答案但似乎没有。 (或者也许我只是不理解它们。)我从来没有使用过反射而几乎没有使用过事件,所以如果它是愚蠢的话就很抱歉。

0 个答案:

没有答案