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.
You need to use
MakeByRefType
method to get the type ofstring&
.Then just compare it with the given type.