【问题标题】:Confusing error when splitting a string拆分字符串时令人困惑的错误
【发布时间】:2013-04-16 04:41:10
【问题描述】:

我有这行代码:

string[] ids = Request.Params["service"].Split(",");

Request.Params["service"] 中的值为:"1,2"

我为什么会得到:

Error   1   The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Error   2   Argument 1: cannot convert from 'string' to 'char[]'

这对我来说毫无意义......

错误发生在等号右边的所有地方

【问题讨论】:

  • split 将一个字符数组或单个字符而不是字符串作为其参数
  • 分割期望一个字符所以','而不是","

标签: c# asp.net-mvc-3 split


【解决方案1】:

您需要传递一个字符 (System.Char),而不是 string:

string[] ids = Request.Params["service"].Split(',');

String.Split 没有重载,需要 params string[] 或单个 string,这是使您的代码正常工作所必需的。

如果您想用一个字符串(或多个字符串)进行拆分,您需要使用 string[] 并指定拆分选项:

string[] ids = Request.Params["service"].Split(new[]{","}, StringSplitOptions.None);

【讨论】:

  • 字符串[] 有一个,但因为他只使用一个字符,所以没关系。 +1。
  • @ofstream 这就是为什么我明确提到params string[],而不是string[] - 尽管string[] 除了数组之外还需要 StringSplitOptions。
【解决方案2】:

你必须使用 params Char[] 的重载:

string[] ids = Request.Params["service"].Split(',');

【讨论】:

    【解决方案3】:

    正如其他人在这里所说,您提供的 (",") 双引号表示一个字符串,Split 函数接受一个字符数组或 char[]。使用 (',') ,单引号表示一个字符。您还可以传递 StringSplitOptions,如果您碰巧在您的 string[] 中得到空值,它需要一个 char[] 与它一起传递,如下所示。

            string splitMe = "test1,test2,";
            string[] splitted1 = splitMe.Split(',');
            string[] splitted2 = splitMe.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            //Will be length 3 due to extra comma
            MessageBox.Show(splitted1.Length.ToString());
            //Will be length 2, Removed the empty entry since there was nothing after the comma
            MessageBox.Show(splitted2.Length.ToString());
    

    【讨论】:

      【解决方案4】:

      在行中 Request.Params["service"].Split(",");

      您将通过"," 而不是',' 拆分

      .Split() 方法接受一个字符数组,而不是字符串

      【讨论】:

        猜你喜欢
        • 2013-05-19
        • 2016-03-24
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 2012-09-12
        • 1970-01-01
        相关资源
        最近更新 更多