Reflection: Get Methods with a Specific Custom Attribute


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

Advertisements

J

Jon Skeet [C# MVP]

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
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Take a look at MemberInfo.GetCustomAttributes method.
 
Ad

Advertisements

A

Alun Harford

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top