我有以下代码:
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);
}
}
这种方法的问题在于m_args本身就是一个对象,其内容不会被展平为单个的params条目。我该如何解决这个问题?
答案 0 :(得分:4)
我认为你错了。 params
似乎按预期工作。这是一个更简单的例子,表明它有效:
static void f(params object[] x)
{
Console.WriteLine(x.Length);
}
public static void Main()
{
object[] x = { 1, 2 };
f(x);
}
结果:
2
查看在线工作:ideone
答案 1 :(得分:0)
这就像你认为的那样。
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 ;
}
}