I have the following method:
public MethodInfo FancyGetMethodInfo
(object obj, string methodName, Type[] methodSignature)
{
return obj.GetType().GetMethod(methodName, methodSignature);
}
and for the sake of an example I have in my object I am passing the two methods
public int Subtract(int a, int b) { return a - b; }
public int Add(params int[] a) { return a.Sum(); }
And when I execute the following lines I get these results:
var SubMethod = FancyGetMethodInfo(obj, "Subtract",
new Type[] { typeof(int), typeof(int) });
//I get a MethodInfo
var AddMethod = FancyGetMethodInfo(obj, "Add",
new Type[] { typeof(int), typeof(int) });
//I get a Null reference
I’m sure this is because of the params in Add. Is there a clean way to get reference to my MethodInfo for my Add method given an arbitrary sized Type[] containing ints and only having access to the provided variables in my FancyGetMethodInfo method?
Edit:
More eloquently put by Jon Skeet, I want to perform the same binding as the C# compiler does in my method. it needs to work properly with subclasses, implicit casting, arbitrary length params, etc…
Also as requested, a relevant link here is: Determining if a parameter uses "params" using reflection in C#? which will get me as far as knowing that the method has a params.
Well, you could:
Note that once you’d found a match (and not found a match that didn’t require this params expansion) you’d then need to remember that so that you could deal with the arguments appropriately later (assuming you want to actually call the method).
It’s a bit of a faff, to be honest… the way I see it you have three options:
typeof(int[])and your existing code will workFancyGetMethodInfoto handle parameter arrays as described aboveSumto accept two integers (or possibly have various overloads)It’s up to you which route you choose…