How can I invoke a varargs method using reflection? Like this one:
public static void ArgsMethod(__arglist)
{
ArgIterator ai = new ArgIterator(__arglist);
while(ai.GetRemainingCount() > 0)
{
Console.WriteLine(TypedReference.ToObject(ai.GetNextArg()));
}
}
typeof(Program).GetMethod("ArgsMethod").Invoke(null,new object[0])
throws NotSupportedException.
Since RuntimeMethodInfo
simply doesn't support this (it explicitly checks and throws if the calling convention of the method is VarArgs
), you'll have to write a wrapper that takes a regular Object[]
, generates IL for calling the method, and invokes that. ILGenerator
does support varargs-methods through EmitCall
. The MSDN is even helpful enough to have a sample that demonstrates this exact scenario.
Of course, it's not exactly convenient, but then nothing about varargs is, really.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With