params keyword and reflection


G

Guest

Hi There -

The code that follows does not work. I'm trying to dynamically invoke a
method that contains a params-attributed parameter. However, the array of
objects that are passed into the method are not put into an array, so the
method signature never matches the object array of parameters. Is there
another way around this without explicitly creating an array (a la new
object[] {new int[] {1, 2, 3}})?

class A
{
public static Main()
{
A a = new A();
a.GetType().GetMethod("Eval").Invoke(null, new object[] { 1, 2, 3
});
}

public static void Eval(params int[] list)
{
int x = 0;
foreach (int i in list)
{
x += i;
}
int total = x;
}
}

Thanks in advance,

Craig
 
Ad

Advertisements

P

Piotr Dobrowolski

Hi There -

The code that follows does not work. I'm trying to dynamically invoke a
method that contains a params-attributed parameter. However, the array
of
objects that are passed into the method are not put into an array, so the
method signature never matches the object array of parameters. Is there
another way around this without explicitly creating an array (a la new
object[] {new int[] {1, 2, 3}})?

class A
{
public static Main()
{
A a = new A();
a.GetType().GetMethod("Eval").Invoke(null, new object[] { 1,
2, 3
});
}

public static void Eval(params int[] list)
{
int x = 0;
foreach (int i in list)
{
x += i;
}
int total = x;
}
}

Thanks in advance,
[PD] The method you used can't work. You are trying to invoke method with
three int parameters and you have method taking one int[] parameter.
Please note that keyword "params" doesn't change resulting method
declaration, it only adds ParamsArray attribute to one of the parameters.
This attribute is information for the compiler, so it knows that if you
call method like this: Eval(1,2,3) it must take the parameters you
provided, pack them into array and call the method. Actually you can also
call your method like this: Eval(new int[]{1,2,3}).
 
Ad

Advertisements

V

Vadym Stetsyak

Hello, csperler!

Eval method wants 1 parameter that is array, and you're trying to pass more then one parameter. To get your code working specify that you're passing array parameter

a.GetType().GetMethod("Eval").Invoke(null, new object[] { new int[] {1, 2, 3} });

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top