Testing whether a method has a specific signature using Reflection

931 views Asked by At

I'm writing an abstract class which (in its constructor) collects all static methods that adhere to a certain signature. The methods it collects must look like:

static ConversionMerit NAME(TYPE1, out TYPE2, out string)

Where I don't care about naming, or the types of the first two parameters, but the second and third parameters must be 'out' parameters and the third one must be of type System.String.

My problem is with the final check for stringness:

MethodInfo[] methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
  foreach (MethodInfo method in methods)
  {
    if (method.ReturnType != typeof(ConversionMerit))
      continue;

    ParameterInfo[] parameters = method.GetParameters();
    if (parameters.Length != 3)
      continue;

    if (parameters[0].IsOut) continue;
    if (!parameters[1].IsOut) continue;
    if (!parameters[2].IsOut) continue;

    // Validate the third parameter is of type string.
    Type type3 = parameters[2].ParameterType;
    if (type3 != typeof(string))   // <-- type3 looks like System.String&
      continue;

    // This is where I do something irrelevant to this discussion.
  }

The ParameterType property of the third ParameterInfo, tells me that the type is System.String&, and comparing it to typeof(string) fails. What is the best way to perform this check? It sounds a bit ham fisted to me to compare the typename using string comparisons.

2

There are 2 answers

0
Selman Genç On BEST ANSWER

You need to use MakeByRefType method to get the type of string&.Then just compare it with the given type.

 if (type3 != typeof(string).MakeByRefType())   
1
Praveen Paulose On

System.String& is returned if your method parameter is passed by ref or is an out parameter. When a string is passed normally, it would show as System.String which would then match with your if condition

if (type3 != typeof(string)) 

In order to compare ref types, you can do this

if (type3 != typeof(string).MakeByRefType())