开发者

C# Method Overload vs Param Keyword

I have a method: relevant part below

void foo(various parameters)
{
   tsk.run(various parameters);
}

Now the parameters with the tsk.run need to spaced as such:

tsk.run(param 1 + " " param2 + " " param3);, etc depending on how many parameters.

The parameters will form one continuous string that is used in a command line app.

At most, there will be 4 parameters, so is it best to do an overload method for each. Or is there a way using the Param keyword to take the parameters开发者_如何学C and add them to the tsk.run() method.

Would it be worth using param[] and then looping through, concatenating into a string and then put that into run?


You needn't loop:

void Foo(params string[] args)
{
    tsk.run(String.Join(" ", args));
}


If you know the number of arguments use overload as it will be more efficient.

The compiler will be able to directly call the right method and you can assign default values.

If the paramlist is created dynamically and can vary more in length, use params.

Or in you example skip params and just use a string list or string array.


well you could do that by using

(params object[] parameters)

then inside method create a Strigbuilder and append each param from list to it in your required fashion.

Its unclear whether your parameters are all strings, or they are really various by type and object signature should be used. If parameters are different by type I think having params method with objects would create more problems than help.

If they are all strings I think params is ideal solution for this situation.


void foo( params string[ ] parameters )
{
    StringBuilder sb = new StringBuilder( );

    foreach ( string parameter in parameters )
    {
        sb.Append( parameter );
        sb.Append( " " );
    }

    tsk.run( sb.ToString( ) );
}


Like this:

void foo<T>(params T[] parameters)
{
    tsk.run(string.Join<T>(" ", parameters));
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜