开发者

How does string.Format table in as many objects as it wants?

I was always under the impression when using String.Format() you could only take 开发者_StackOverflow社区3 objects in before you would have to use an array of objects.

Recently I discovered this is not the case and you can put as many as you want.

How can this be done? Does it do some like dynamic overloading or does it convert it all into an array.

//thought this was the max that could be sent in
String.Format(String, Object, Object, Object);
//before you had to do something like this

object[] format = new object[5];
format[0] = "abc";
...
String.Format(String, format);

// yet it seems you can do
String.Format(String, Object, Object, Object, Object, Object, Object, Object, Object, Object);


This is what the params keyword is for. An arbitrary number of arguments is allowed. The method is written to accept an array. The compiler inserts the array creation for you.


It uses the params keyword on a method parameter. So the method definition looks like:

public static string Format(string input, params object[] values)
{
}

You can call the function as though it has n parameters but it gets passed in to the method as an array.


Using the params keyword, you can write methods that take variable numbers of arguments from the perspective of the caller and the compiler converts it to an array from the perspective of the callee.


It uses the params keyword

 public static string Format(string template,params object[] data)
{
    //
}


MSDN Reference:

params (C# Reference)

void Method(params object[] objs)
{
    // use objs
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜