简体   繁体   English

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

[英]String.Split() method: compiler chooses wrong overload

I have the following code:我有以下代码:

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 any 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.我正在使用String.Split()方法。 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.根据MSDN ,这种方法有很多重载。 The default String.Split() with no parameters calls this overload:没有参数的默认String.Split()调用此重载:

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

There is an overload which doesn't return the empty tokens:有一个不返回空标记的重载:

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 .据我了解,为了使其不返回空标记,第二个参数必须是StringSplitOptions.RemoveEmptyEntries So the intuitive way to call this is:所以直观的调用方式是:

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

The compiler, however, thinks otherwise, and throws error CS1503 at me:然而,编译器不这么认为,并向我抛出错误 CS1503:

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

So it's obvious that the compiler is not choosing the overload I want.所以很明显编译器没有选择我想要的重载。 Hovering over the function calls makes IntelliSense show me this:将鼠标悬停在 function 调用上会使 IntelliSense 向我显示:

string[] Split(params char[] separator)

How should I call String.Split() in order to call the overload I want?我应该如何调用String.Split()来调用我想要的重载?

In .NET Framework use在 .NET 框架中使用

char[] charSeparators = new char[] { ' ' };
string[] tok = s.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);

In NET core (I test in 2.2).在 NET 核心中(我在 2.2 中测试)。 the code is working代码正在运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM