web-dev-qa-db-fra.com

Rechercher des méthodes ayant un attribut personnalisé à l'aide de la réflexion

J'ai un attribut personnalisé:

public class MenuItemAttribute : Attribute
{
}

et une classe avec quelques méthodes:

public class HelloWorld
{
    [MenuItemAttribute]
    public void Shout()
    {
    }

    [MenuItemAttribute]
    public void Cry()
    {
    }

    public void RunLikeHell()
    {
    }
}

Comment puis-je obtenir uniquement les méthodes décorées avec l'attribut personnalisé?

Jusqu'à présent, j'ai ceci:

string assemblyName = fileInfo.FullName;
byte[] assemblyBytes = File.ReadAllBytes(assemblyName);
Assembly assembly = Assembly.Load(assemblyBytes);

foreach (Type type in Assembly.GetTypes())
{
     System.Attribute[] attributes = System.Attribute.GetCustomAttributes(type);

     foreach (Attribute attribute in attributes)
     {
         if (attribute is MenuItemAttribute)
         {
             //Get me the method info
             //MethodInfo[] methods = attribute.GetType().GetMethods();
         }
     }
}

Ce dont j'ai besoin maintenant, c'est d'obtenir le nom de la méthode, le type de retour, ainsi que les paramètres qu'il accepte.

46
stoic

Votre code est complètement faux.
Vous parcourez chaque type qui a l'attribut, qui ne trouvera aucun type.

Vous devez parcourir chaque méthode sur chaque type et vérifier si elle a votre attribut.

Par exemple:

var methods = Assembly.GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                      .ToArray();
83
SLaks
Dictionary<string, MethodInfo> methods = Assembly
    .GetTypes()
    .SelectMany(x => x.GetMethods())
    .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any())
    .ToDictionary(z => z.Name);
21
JordanBean
var class = new 'ClassNAME'();
var methods = class.GetType().GetMethods().Where(m=>m.GetCustomAttributes(typeof(MyAttribute), false).Length > 0)
.ToArray();

Vous avez maintenant toutes les méthodes avec cet attribut 'MyAttibute' en classe. Vous pouvez l'invoquer n'importe où.

public class 'ClassNAME': IDisposable
 {
     [MyAttribute]
     public string Method1(){}

     [MyAttribute]
     public string Method2(){}

     public string Method3(){}
  }
0
Unknown Artist