为什么"my,string".Split(',')在.NET C#中工作?
根据MSDN声明Split是Split(Char[]).
MSDN String.Split方法
我认为C#5将单个字符转换','为char[] {','}; 但我一定是错的,因为以下代码不起作用:
static void Main()
{
GetChar(',');
}
static char GetChar(char[] input)
{
return input[0];
}
Run Code Online (Sandbox Code Playgroud)
编辑:感谢Jon Skeet的回答,我改变了论点params char[],它证明了这个概念.
static char GetChar(params char[] input)
{
return input[0];
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 23
您正在使用的重载基本上使用参数数组.这就是这个params部分.编译器会自动将您的单个参数包装到数组中.所以这:
var x = text.Split(',');
Run Code Online (Sandbox Code Playgroud)
相当于:
var x = text.Split(new char[] { ',' });
Run Code Online (Sandbox Code Playgroud)
您也可以使用参数数组为您自己的方法,使用params关键字:
static char GetChar(params char[] input)
{
return input[0];
}
Run Code Online (Sandbox Code Playgroud)
请注意,参数数组必须是最终参数.这就是为什么你使用的重载是使用参数数组的唯一重载Split.看看其他重载:
Split(Char[], Int32)
Split(Char[], StringSplitOptions)
Split(String[], StringSplitOptions)
Split(Char[], Int32, StringSplitOptions)
Split(String[], Int32, StringSplitOptions)
Run Code Online (Sandbox Code Playgroud)
在每种情况下,数组都是第一个参数,因此您必须自己构造一个数组:
var x = text.Split(new char[] { ',' }, 10); // Call the (char[], int) overload
Run Code Online (Sandbox Code Playgroud)
或者使用隐式类型数组:
var x = text.Split(new[] { ',' }, 10); // Call the (char[], int) overload
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1143 次 |
| 最近记录: |