views:

728

answers:

2

Suppose I've got the following program:

namespace ReflectionTest
{
    public class Example
    {
        private string field;

        public void MethodOne() { }

        public void MethodTwo() { }

        public string Property
        {
            get { return field; }
            set { this.field = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            iterate(typeof(Example));

            Console.ReadLine();
        }

        public static void iterate(Type type)
        {
            MethodInfo[] methods = type.GetMethods(
                BindingFlags.DeclaredOnly |
                BindingFlags.Instance |
                BindingFlags.Public);

            foreach (MethodInfo mi in methods)
            {
                Console.WriteLine(mi.Name);
            }
        }
    }
}

When I run the program I'm getting the following output:

MethodOne
MethodTwo
get_Property
set_Property

I want to skip the property accesor methods. I've tried with different BindingFlags, for instance, ~BindingFlags.SetProperty, but with no luck. At the moment the only way I've found to skip those methods is rewriting the iterate function to:

public static void iterate(Type type)
{
    MethodInfo[] methods = type.GetMethods(
        BindingFlags.DeclaredOnly |
        BindingFlags.Instance |
        BindingFlags.Public);

    foreach (MethodInfo mi in methods)
    {
        if (mi.IsSpecialName) continue;
        Console.WriteLine(mi.Name);
    }
}

Do you know what BindingFlags should I use?

Thank you very much.

+2  A: 

From the top of my head:

mi.IsSpecialName &&( mi.Name.StartsWith("set_") || mi.Name.StartsWith("get_"))

should get you all set. SpecialName is more than property accessors (event add/remove methods count here as well), that's why you have to check the names as well.

You can use LINQ for that as well :)

Krzysztof Koźmic
A: 

Well, I should have explained that the project is actually for building automatically templates for unit testing, so I can skip all the special methods. Thanks for the additional information on IsSpecialName :)

LINQ? Really? Wow. Anyway, this project is .NET 2.0 so LINQ is (sadly) not an option.

Leandro López