开发者

Calling method with params from method with params

开发者 https://www.devze.com 2023-04-12 05:50 出处:网络
I want to do the ne开发者_运维知识库xt: void SomeMethod () { ParamMethod1 (1,2,3); } void ParamMethod1 (params object[] arg)

I want to do the ne开发者_运维知识库xt:

void SomeMethod ()
{
  ParamMethod1 (1,2,3);
}

void ParamMethod1 (params object[] arg)
{
   ParamMethod2 (0, arg); //How to call ParamMethod2 in order to it works 
   //as I want
}

void ParamMethod2 (params object[] arg)
{
  //I want 'arg' contains 0,1,2,3 instead of 0, System.object[]
}

Thanks for any help.


You can do it with LINQ but you need still need ToArray()

ParamMethod2(new object [] { 0 }.Concat(arg).ToArray());

Edited to Add:

Based on the comment regarding performance I did some very basic performance comparisons between the suggested methods.

For 1 million calls

80ms -- Direct call: ParamMethod2(0,1,2,3);
280ms -- Using CopyTo
400ms -- Using LINQ
590ms -- Using AddRange

Of course if you changed object to int and a few other things you will improve performance further. Personally I'd use LINQ because it is fast enough for 99% of cases and in the other case I wouldn't use params in the first place.


One way, though not necessarily ideal, could simply be:

void ParamMethod1 (params object[] arg)
{
    var args = new List<object>();
    args.Add(0);
    if (arg != null)
    {
        args.AddRange(arg);
    }        
    ParamMethod2(args.ToArray());
}

That is to say, regardless of how this is done, we need to combine 0 and the contents of arg into a single collection - there will doubtless be a more efficient way, and perhaps even a simpler approach that I can't see for lack of coffee this morning, but this will do the trick, so to speak.


Change this method

void ParamMethod2 (params object[] arg) { //I want 'arg' contains 0,1,2,3 instead of 0, System.object[] }

To

void ParamMethod2 (int firstValue, params object[] arg) { //Now, firstvalue always will have 0 and remaining passed variables will have 1,2,3, etc. }

Hope this is what your asking for.

Note here that you will have a problem if you want to have a method with only params as arguments, because always your compiler will call this explicit first argument signature than params only signature method.


void ParamMethod1 (params object[] arg)
{
   if(arg == null || arg.Length == 0)
   {
      ParamMethod2(0);
      return;
   }
   var newArray = new int[arg.Length + 1];
   newArray[0] = 0;
   arg.CopyTo(newArray,1);
   ParamMethod2 (newArray); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号