views:

18

answers:

1

Hey There

I have a custom attribute :

public class MenuItemAttribute : Attribute
{
}

and i have a class with a few methods:

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

    [MenuItemAttribute]
    public void Cry()
    {
    }

    public void RunLikeHell()
    {
    }
}

Using reflection, how can i get only the methods that are decorated with the custom attribute?

So far i have this:

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();
                        }
                    }
                }

What i need now is to get the method name, the return type, as well as the parameters it accepts.

+1  A: 

Your code is completely wrong.
You are looping through every type that has the attribute, which will not find any types.

You need to loop through every method on every type and check whether it has your attribute.

For example:

var methods = assembly.GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                      .ToArray();
SLaks
am i doing it ass-about-front here? cause right now i look for all the attributes and i then try and get the associated method
Dusty Roberts
strangly enough with my code i get 2 results, but with your example i get 0.....
Dusty Roberts
I tried it with your classes; it works for me. Are you searching the right assembly?
SLaks
doh... changed some of the code to make it simple for stackoverflow readers... never changed it back...thanx... yours is correct
Dusty Roberts