Reflection: Get Methods with a Specific Custom Attribute

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

The code below goes through all the methods in the given dll. I'm wondering
how I can modify this to only get methods with a specific custom attribute.
I'm not seeing any Custom Attributes like [TestMethod()] when I print out the
attributes.

Thanks,
Randy

Assembly a = Assembly.LoadFile(s);
Type[] types = a.GetTypes();

foreach (Type t in types)
{
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo m in methods)
{
MethodAttributes ma = m.Attributes;
Console.WriteLine(ma.ToString());
}
}
 
The code below goes through all the methods in the given dll. I'm wondering
how I can modify this to only get methods with a specific custom attribute.
I'm not seeing any Custom Attributes like [TestMethod()] when I print out the
attributes.

You need to call GetCustomAttributes(), not use the Attributes
property. The latter is just for things like "abstract" and "virtual".

Note also that if you want to get non-public methods, you'll need to
specify a BindingFlags in the call to GetMethods().

Jon
 
randy1200 said:
The code below goes through all the methods in the given dll. I'm wondering
how I can modify this to only get methods with a specific custom attribute.
I'm not seeing any Custom Attributes like [TestMethod()] when I print out the
attributes.

a) As has been said, you need to use MemberInfo.GetCustomAttributes(...)
b) You probably also want to look into MemberInfo.IsDefined(...)

Alun Harford
 
Back
Top