How do I pass an object array into a method as individual parameters?

7.9k views Asked by At

I have the following code:

public class MyClass
{
    private Delegate m_action;
    public object[] m_args;

    public MyClass()
    {

    }

    public MyClass(Delegate action, params object[] args)
    {
        m_args = args;
        m_action = action;
    }

    public void Execute()
    {
        m_action.DynamicInvoke(m_args);
    }
}

The problem with this approach is that the m_args is an object itself, and its contents are not being flattened out into individual params entries. How can I fix this?

2

There are 2 answers

0
Mark Byers On BEST ANSWER

I think you are mistaken. The params seems to work as intended. Here's a simpler example showing that it works:

static void f(params object[] x)
{
    Console.WriteLine(x.Length);
}

public static void Main()
{
    object[] x = { 1, 2 };
    f(x);
}

Result:

2

See it working online: ideone

0
Nicholas Carey On

This works just like you'd think it would.

public class MyClass
{
  private Delegate m_action;
  public object[] m_args;

  public MyClass()
  {
  }

  public MyClass( Delegate action , params object[] args )
  {
    m_args = args;
    m_action = action;
  }

  public void Execute()
  {
    m_action.DynamicInvoke( m_args );
  }
}

class Program
{
  static void Main( string[] args )
  {
    Type       tSelf          = typeof(Program) ;
    MethodInfo mi             = tSelf.GetMethod( "FooBar" ) ;
    Delegate   methodDelegate = Delegate.CreateDelegate( typeof(Action<int,int,int>) , mi ) ;
    MyClass    instance      = new MyClass( methodDelegate , 101 , 102 , 103 ) ;

    instance.Execute() ;

    return;
  }

  public static void FooBar( int x , int y , int z )
  {
    Console.WriteLine( "x:{0}, y:{1}, z:{2}" , x , y , z ) ;
    return ;
  }

}