开发者

C#: Converting a collection into params[]

Here is a simplification of my code:

void Foo(params object[] args)
{
    Bar(string.Format("Some {0} text {1} here {2}", /* I want to send args */);
}

string.Format requires the arguments sent as params. Is there s开发者_StackOverflow社区ome way I can convert the args collection into parameters for the string.Format method?


The params keyword is only syntactic sugar that allows you to call such a method with any number of arguments. However, those arguments are always passed to the method as an array.

This means that Foo(123, "hello", DateTime.Now) is equivalent to Foo(new object[] { 123, "hello", DateTime.Now }).

You can therefore pass the arguments from Foo directly to string.Format like this:

void Foo(params object[] args)
{
  Bar(string.Format("Some {0} text {1} here {2}", args));
}

However, in this particular case, you demand three arguments (because you have {0}, {1} and {2} in your format). Therefore you should change your code to:

void Foo(object arg0, object arg1, object arg2)
{
  Bar(string.Format("Some {0} text {1} here {2}", arg0, arg1, arg2));
}

...or do as Marcelo suggested.


Pass them in as a single argument:

Bar(string.Format("Some {0} text {1} here {2}", args));


You could try using object.GetType(), for example

void Foo(params object[] args)
    {
        List<string> argStrings = new List<string>();

        foreach (object arg in args)
        {
            if (args.GetType().Name == typeof(String).Name)
            {
                argStrings.Add((string)arg);
            }
            else if (args.GetType().Name == typeof(DateTime).Name)
            {
                DateTime dateArg = (DateTime)arg;
                argStrings.Add(dateArg.ToShortDateString());
            }
            else
            {
                argStrings.Add(arg.ToString());
            }
        }

        Bar(string.Format("Some {0} text {1} here {2}", argStrings.ToArray()));
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜