tags:

views:

99

answers:

4

My intention is to investigate the "Methods" of a Type using reflection in order to verify the following :

  1. The Methods should be instance methods and public.

  2. Takes the parameter "params" and void in nature.

  3. The Method does not makes recursive call.

I started as :

static void ProcessMethodInfo(Type t)
    {
        MethodInfo[] info = t.GetMethods();

        foreach (MethodInfo mi in info)
        {

          // How to check the conditions here ?  

        }
    }

But I don't know how to proceed further. Help is needed.

A: 

I don't think you'll be able to detect item 3 using reflection.

Steven Sudit
+3  A: 

Well, if by 3 you mean the method under inspection should be non-recursive; then that is a pain - you'd need to parse the IL. But for the others;

    Type type = ...
    var qry = from method in type.GetMethods(
                  BindingFlags.Instance | BindingFlags.Public)
              where method.ReturnType == typeof(void)
              let parameters = method.GetParameters()
              where parameters.Length == 1
              && parameters[0].ParameterType.IsArray
              && Attribute.IsDefined(parameters[0], typeof(ParamArrayAttribute))
              select method;
    foreach (var method in qry)
    {
        Console.WriteLine(method.Name);
    }
Marc Gravell
I think using == to compare instances of classes should be avoided. Equals might be overridden, but == usually isn't overloaded.
Joren
You mean for `Type`? That is perfectly valid. I know what you are saying, but the code is fine.
Marc Gravell
Excellent Marc.Thank you very much.
I wasn't saying the code is incorrect. I was saying using == to compare instances of classes should generally be avoided, because most of the time it's not correct. It's a minor point anyway, but I thought I might just as well leave a comment.
Joren
You were right to do so; I've made the exact same comment in the past ;-p
Marc Gravell
+1  A: 
  1. mi.IsStatic, etc - read help
  2. http://stackoverflow.com/questions/627656/determining-if-a-parameter-uses-params-using-reflection-in-c
  3. http://www.codeproject.com/KB/cs/sdilreader.aspx

ALL: use google ;)

queen3
Thank you very much :)
A: 

Check the following members of the MethodInfo class:

  • IsPublic
  • IsStatic
  • ReturnType
  • GetParameters() method

In order to be able to check whether the method is recursive, I think you'll need something more then just simple reflection.

Frederik Gheysels