9

I'm doing a runtime assembly load, but i don't know the names of any classes or methods. I wan't to list all classes in my assembly with their declared methods, not those inherited from System.Object.

This is the code:

string str = "";   
Assembly assembly = Assembly.LoadFile(@"c:\components.dll");    

foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass == true)
    {    
        str += type.Name + "\n";    
        MethodInfo[] methodInfo = type.GetMethods(BindingFlags.DeclaredOnly);

        foreach (MethodInfo mi in methodInfo)
        {    
            str += "\t" + mi.Name + "\n";    
        }    
    }
}

MessageBox.Show(str);

This is the components.dll:

public class component01
{    
    public string myName = "component01";
    public string getMyName()
    {
        return myName;
    }
}

public class component02
{    
    public string myName = "component02";

    public string getMyName()
    {
        return myName;
    }
}

The result:

component01
component02

And if i remove the bindingflag:

component01
   getMyName
   ToString
   Equals
   GetHashcode
   GetType
component02
   getMyName
   ToString
   Equals
   GetHashcode
   GetType

I only want the getMyName method shown.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Bildsoe
  • 1,310
  • 6
  • 31
  • 44

1 Answers1

15

I think you're looking for the flags:

BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly

You may want to put in BindingFlags.NonPublic as well, depending on your requirements.

I would also point out that with deeper inheritance hierarchies, types can inherit members from base-types other than System.Object. If you want to keep those, but not the ones originally declared on object, you could:

  1. Remove the BindingFlags.DeclaredOnly flag for the GetMethods call.
  2. Only include methods for which:

    methodInfo.GetBaseDefinition().DeclaringType != typeof(object)
    

Of course, you may need a different filter if your definition of "declared" method were more complicated.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • 1
    Works perfectly, thanks! I tried using both Public and DeclaredOnly previously, but this didn't work. How come i need to specify all three? – Bildsoe Jan 27 '11 at 08:41
  • @Bildsoe: `System.Reflection.BindingFlags` is a flags-enum. When the `Instance` flag is not set, `GetMethods` doesn't include instance methods. – Ani Jan 27 '11 at 08:46
  • 1
    ok, thanks. I just thought that, if the method was any of the mentioned it would get included. – Bildsoe Jan 27 '11 at 08:48
  • 1
    @Bildsoe: Yes, it is a little unintuitive isn't it - `Instance` works as an inclusive filter, but `DeclaredOnly` is exclusive. – Ani Jan 27 '11 at 09:06
  • Yes, a little. But of course when reading the documentation on MSDN, i can see that it is described here. – Bildsoe Jan 27 '11 at 09:39