Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Supposing we have the following example class:</p> <pre><code>public class Test { public static int Add(int i1, int i2) { return i1 + i2; } public static int Add(params int[] ints) { int sum = 0; foreach (int i in ints) sum += i; return sum; } } </code></pre> <p>To get the <code>MethodInfo</code> objects for each overload of the static <code>Add</code> method you should do the following:</p> <pre><code> MethodInfo Add2Ints = typeof(Test).GetMethod("Add", new Type[] { typeof(int), typeof(int) }); MethodInfo AddParamsInts = typeof(Test).GetMethod("Add", new Type[] { typeof(int[]) }); </code></pre> <p>In order to invoke any of the two methods, symply pass the arguments with the exact type expected by the specific overload you are invoking:</p> <pre><code> Add2Ints.Invoke(null, new object[] { 1, 2 }); AddParamsInts.Invoke(null, new object[] { new int[] { 1, 2 } }); </code></pre> <p>Note that the following will not work:</p> <pre><code> AddParamsInts.Invoke(null, new object[] { 1, 2 }); </code></pre> <p>because the signature of <code>AddParmsInt</code> is really <code>(int[])</code> and although the compiler, as a courtesy, <em>allows</em> you to call such method as <code>(int, int)</code> under the hood what is really happening is that the call is converted for you at the call site to the equivalent <code>(int[])</code> call. Via reflection you don't have the compiler's "help" so you need to pass the <em>exact</em> argument type defined by the method's signature.</p> <p>With all that said, your <code>call</code> method should be as follows:</p> <pre><code> public object call(params object[] input) { return AddParamsInts.Invoke(null /*static*/, new object[] { input.Cast&lt;int&gt;().ToArray() }); } </code></pre> <p>Note that you can not directly cast a <code>object[]</code> array to a <code>int[]</code> array: <code>int[] ints = (int[])input</code>. Casting <em>reference</em> typed <em>arrays</em> to <em>value-type</em> arrays is not allowed.</p> <p>Also important to note is that the defined overloads of the <code>Add</code> method are useless, as they overlap. Consider only using the <code>params</code> overload or, in case you want to guarantee that at least two arguments are needed in order to evaluate an <em>addition</em>, overload them the following way:</p> <pre><code> public int Add(int i1, int i2) { } public int Add(int i1, int i2, params int[] args) { } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload