user2115640
user2115640

Reputation: 5

Getting all the Methods from a dll in an array or list

I'm using reflection to get all the methods from a particular dll that is decorated with a custom attribute. However im not able to get all those methods in an arraylist or a list for it says like this "cannot convert from 'string' to 'System.Collections.ICollection'".

The Code is as below

public static void Main(string[] args)
{
 var methods = type.GetMethods(BindingFlags.Public);
               foreach (var method in type.GetMethods())
                 {
                var attributes = method.GetCustomAttributes(typeof(model.Class1), true);
                                if (attributes.Length != 0)
                                {

                                    for(int i=0;i<attributes.Length; i++)
                                    {
                                       ArrayList res = new ArrayList();
                                       res.AddRange(method.Name);
                                       listBox1.DataSource = res;
 }                                   }
}
}

Upvotes: 0

Views: 97

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500465

Your current code is all over the place, I'm afraid.

  • You're binding against a new list with a single entry for every attribute in every method, instead of collecting all the method names and then binding once
  • You're calling AddRange with a single value
  • Your methods variable is completely unused, and it will be empty anyway as you're neither specifying Instance or Static binding flags

I would suggest using LINQ for this, and MemberInfo.IsDefined, and definitely avoid using ArrayList. (Non-generic collections are so 2004...)

var methods = type.GetMethods()
                  .Where(method => method.IsDefined(typeof(model.Class1), false)
                  .Select(method => method.Name)
                  .ToList();
listBox1.DataSource = methods;

I'd also suggest changing your attribute name from model.Class1 to something that follows .NET naming conventions and indicates the meaning of the attribute...

Upvotes: 2

Jonysuise
Jonysuise

Reputation: 1830

Create a generic list instead of an array to store method names.

Upvotes: 1

Related Questions