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

人走茶凉 提交于 2019-12-13 01:27:24

问题


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?


回答1:


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




回答2:


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 ;
  }

}


来源:https://stackoverflow.com/questions/12167924/how-do-i-pass-an-object-array-into-a-method-as-individual-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!