C# 字符串数组拆分无效参数
C# string array split invalid arguments
为什么编译没有错误:
string input = "one two one three one";
string[] numbers = { "one", "two", "three", "four" };
string[] workingSplitTest = input.Split(new string[] { "one" }, StringSplitOptions.None);
然而这会产生无效参数错误 ("The best overloaded method match for 'string.Split(string[], System.StringSplitOptions)' has some invalid arguments"):
string input = "one two one three one";
string[] numbers = { "one", "two", "three", "four" };
string[] brokenSplitTest = input.Split(numbers[0], StringSplitOptions.None);
这两种方法都引用了字符串数组定界符。我在这里缺少一些基本的东西吗?我需要做哪些更改才能使第二种方法生效?
在第一个示例中,您传递了带有元素 one
的 string array
。
在第二个示例中,您将字符串文字 one
作为参数传递。
documentation 指出它需要一个字符串数组,而不是文字。
new string[] { "one" }
不能与 numbers[0]
互换
这里使用索引数组值的正确方法是:
new string[] { numbers[0] }
当您对数组 numbers[0]
进行索引时,结果是单个字符串 -"one"。
一种选择 - 如果您需要原样的数字数组 - 是这样写的:
string[] brokenSplitTest = input.Split(new string[] { numbers[0] }, StringSplitOptions.None);
否则就选择第一个选项。
为什么编译没有错误:
string input = "one two one three one";
string[] numbers = { "one", "two", "three", "four" };
string[] workingSplitTest = input.Split(new string[] { "one" }, StringSplitOptions.None);
然而这会产生无效参数错误 ("The best overloaded method match for 'string.Split(string[], System.StringSplitOptions)' has some invalid arguments"):
string input = "one two one three one";
string[] numbers = { "one", "two", "three", "four" };
string[] brokenSplitTest = input.Split(numbers[0], StringSplitOptions.None);
这两种方法都引用了字符串数组定界符。我在这里缺少一些基本的东西吗?我需要做哪些更改才能使第二种方法生效?
在第一个示例中,您传递了带有元素 one
的 string array
。
在第二个示例中,您将字符串文字 one
作为参数传递。
documentation 指出它需要一个字符串数组,而不是文字。
new string[] { "one" }
不能与 numbers[0]
这里使用索引数组值的正确方法是:
new string[] { numbers[0] }
当您对数组 numbers[0]
进行索引时,结果是单个字符串 -"one"。
一种选择 - 如果您需要原样的数字数组 - 是这样写的:
string[] brokenSplitTest = input.Split(new string[] { numbers[0] }, StringSplitOptions.None);
否则就选择第一个选项。