dimanche 12 avril 2020

How to provide bind target for methodinfo when using custom attributes?

Im using attributes to get all my methods and wrap them in some delegates. It looks like this:

        var assembly = Assembly.GetExecutingAssembly();
        var methods = assembly.GetTypes()
                  .SelectMany(t => t.GetMethods())
                  .Where(m => m.GetCustomAttributes(typeof(T), false).Length > 0)
                  .ToArray();
        foreach (var m in methods)
        {
            var attr = (T)m.GetCustomAttribute(typeof(T));
            string name = attr.eventName;
            if (name == null) name = m.Name;
            if (m.ReturnType == typeof(void))
            {
                var d = (ServerCallbackAction)Delegate.CreateDelegate(typeof(ServerCallbackAction), null, m);
                if (typeof(T) == typeof(CEFRequestAttribute))
                    Bridge.Instance.OnCEFRequest(name, d);
                else Bridge.Instance.OnClientRequest(name, d);
            }

The problem is, this delegates could not access the instance of DeclaringType, so, how should i bind them? And i can't use Activator.CreateInstance because my instances are creating by another attributes and i do not need to create them again.
Are there any other ways to create delegate/action from methodinfo? Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire