Undocumented overload of string.Split()?

2019-06-16 19:40发布

According to both Intellisense and MSDN doc on string.Split, there are no parameterless overloads of string.Split. Yet if I type in

string[] foo = bar.Split();

It compiles. And it works. I have verified this in both Visual Studio 2008 and 2010. In both cases intellisense does not show the parameterless overload.

Is there a reason for this? Are there any other missing overloads from the MSDN/Intellisense docs? Usually browsing through overloads in intellisense is how I best determine which overload to use. I'd hate to think I am missing other available options throughout the .Net framework.

EDIT: as shown above, it splits on whitespace.

6条回答
Emotional °昔
2楼-- · 2019-06-16 19:50

That is because Split has a params overload. Giving no parameters is the same as giving an empty array. In other words, you are calling this overload.

"some text".Split();

Is the same as:

"some text".Split(new char[0]);

Here is the documentation on the params keyword. As you probably know, it is used for giving a method a variable number of parameters. That number may be zero.

查看更多
看我几分像从前
3楼-- · 2019-06-16 19:54

It has to do with a weakness of exposing parameters as 'params array[]'. See the signature of the following method as documented in MSDN, so obviously you are passing in an empty array.

public string[] Split(params char[] separator)
查看更多
beautiful°
4楼-- · 2019-06-16 20:01
public string[] Split(params char[] separator)

params is 0 or more

查看更多
爷、活的狠高调
5楼-- · 2019-06-16 20:05

Actually what you are calling here is string.Split(params char[] separator)

params (C# reference)

You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

查看更多
太酷不给撩
6楼-- · 2019-06-16 20:06

I bet it's matching this String.Split overload:

public string[] Split(params char[] separator)
{
    return this.Split(separator, 0x7fffffff, StringSplitOptions.None);
}

0 arguments is acceptable for this function. Given no separators, it defaults to white space.

查看更多
别忘想泡老子
7楼-- · 2019-06-16 20:06

String.Split() has a number of overloads; you are correct that none of those overloads is parameter-less, however, one of them is varadic: String.Split(params char[]). The variable length portion of the argument list can be any number of arguments, including zero -- that is the overload you're invoking here.

查看更多
登录 后发表回答