String StartsWith()任何方法避免2次检查?

Dav*_*een 2 c#

我有这个代码.当时并不明显,但所写的代码总是会选择第一个选项,因为"fc"和"fcip"都以"fc"开头.

string fcportdelimit = "fc";
string fcipportdelimit = "fcip";

if (BlockToProcess[0].StartsWith(fcportdelimit)) 
{
    try
    {
        this.ParseFCInterface(BlockToProcess);
    }
    catch (Exception E)
    {
        throw;
    } 
}
else if (BlockToProcess[0].StartsWith(fcipportdelimit)) 
{
    try
    {
        this.ParseFCIPInterface(BlockToProcess);
    }
    catch (Exception E)
    {
        throw;
    } 
}
Run Code Online (Sandbox Code Playgroud)

我查看了字符串类,但没有看到将模式作为输入的StartsWith()或Contains().我正在测试的字符串要么是patttern fcN/N,要么是fcipN,其中N是数字.所以,我想我必须做这样的事情?

if (BlockToProcess[0].StartsWith(fcportdelimit || fcipportdelimit) 
{ 
    if (BlockToProcess[0].StartsWith(fcipportdelimit)
    { 
       // do something here
    } 
    else
    { 
       //since fcipportdelimit didn't match it must be an fcport
       //so do something else
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

我发现正则表达式很容易.以下是Regex.IsMatch的示例:

if (Regex.IsMatch(str, "^(?:fc|fcip)") {
  ...
}
Run Code Online (Sandbox Code Playgroud)

^说"主播到开始"(或"打头")时,|说"非此即彼",并且(?:...)是进行分组.

但是,由于每个匹配调用两种不同的方法,为什么不把它留下来呢?我删除了额外的代码,以便更容易看到.

正如康拉德指出的那样,条件的顺序很重要.

var command = BlockToProcess[0];
if (command.StartsWith("fcip")) {
    this.ParseFCIPInterface(BlockToProcess); // ParseFCIP
} else if (command.StartsWith("fc") {
    this.ParseFCInterface(BlockToProcess);   // ParseFC
}
Run Code Online (Sandbox Code Playgroud)

快乐的编码.


Kon*_*lph 6

鉴于这StartsWith("fcip") 意味着 StartsWith("fc"),只需先测试后者并嵌套第二次测试.

此外,您的try块是完全冗余的,不起作用.

if (BlockToProcess[0].StartsWith(fcportdelimit) { 
    if (BlockToProcess[0].StartsWith(fcipportdelimit) { 
        // do something here
    }
    else {
        // do something here
    }
}
Run Code Online (Sandbox Code Playgroud)

(当然,第二次检查仍然包含冗余部分,因为它会fc再次检查,但重构此检查只会使代码的可读性降低,并不一定会使性能受益.)