String.Split()方法:编译器选择错误的重载

我有以下代码:

using System;

class Token
{
    static void Main()
    {
        Console.Write("Enter string to tokenize: ");
        string s = Console.ReadLine();
        Console.WriteLine("\nString length: {0}\n\nTokens:", s.Length);
        string[] tok = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); //<-- this line causes CS1503
        //string[] tok = s.Split(); //works but also returns empty entries
        foreach (string i in tok)
            Console.WriteLine("{0}", i);
        Console.Write("\n{0} tokens found\nPress Enter key to continue . . . ", tok.Length);
        Console.ReadKey();
    }
}

The code is supposed to take a string from the console input and split it into tokens (separated by spaces). I am using the String.Split() method. By default, this method returns all the empty tokens (if there are multiple consecutive separators), which is something I don't want. According to MSDN this method has a bunch of overloads. The default String.Split() with no parameters calls this overload:

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

有一个不返回空令牌的重载:

public string[] Split(char separator, StringSplitOptions options = System.StringSplitOptions.None);

From what I understand, in order to make it not return empty tokens, the second parameter has to be StringSplitOptions.RemoveEmptyEntries. So the intuitive way to call this is:

s.Split(' ', StringSplitOptions.RemoveEmptyEntries);

但是,编译器认为不正确,并向我抛出错误CS1503:

CS1503: Argument 2: cannot convert from 'System.StringSplitOptions' to 'char'

因此很明显,编译器没有选择我想要的重载。将鼠标悬停在函数调用上可使IntelliSense向我显示以下内容:

string[] Split(params char[] separator)

How should I call String.Split() in order to call the overload I want?

评论