Undocumented overload of string.Split()?

自闭症网瘾萝莉.ら 提交于 2019-12-23 08:57:38

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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)



回答5:


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.




回答6:


public string[] Split(params char[] separator)

params is 0 or more



来源:https://stackoverflow.com/questions/2906621/undocumented-overload-of-string-split

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!