困惑于?:操作人员

本文关键字:操作 | 更新日期: 2023-09-27 18:07:36

我有这个代码:

if (!codeText.StartsWith("<p>"))
{
    codeText = string.Concat("<p>", codeText, "</p>");
}

如何使用?:运算符?

困惑于?:操作人员

由于条件运算符需要else子句,您需要告诉它使用原始值:

codeText = codeText.StartsWith("<p>") ? codeText : "<p>" + codeText + "</p>";

然而,这样做毫无意义;只是更令人困惑。

codeText = codeText.StartsWith("<p>") ?
               codeText :
               string.Concat("<p>", codeText, "</p>");

在这种情况下,使用三元运算符没有多大意义。我会坚持你们现在的if语句。通常,您会在赋值语句中使用三元运算符,或者在不能使用典型if语句的地方使用。

然而,如果你真的想,你可以这样做。

codeText = !codeText.StartsWith("<p>") ? string.Concat("<p>", codeText, "</p>") : codeText; 

这是三元运算符的MSDN页面。http://msdn.microsoft.com/en-US/library/ty67wk28%28v=VS.80%29.aspx

variable=条件?条件为true时的值:条件为false时的值

codeText = (!codeText.StartsWith("<p>")?string.Concat("<p>", codeText, "</p>"):codeText);

你可以这样做:

codeText = codeText.StartsWith("<p>")
    ? codetext
    : string.Concat("<p>", codeText, "</p>");

但我不知道你为什么要那样做。

像这样:

codeText = codeText.StartsWith("<p>") ? codeText : string.Concat("<p>", codeText, "</p>");

如果它相当长,我通常会像这样写多行:

codeText = codeText.StartsWith("<p>")
  ? codeText
  : string.Concat("<p>", codeText, "</p>");

尽管我不得不承认,但我看不出使用?:运算符,假设您没有其他情况,则必须添加一个执行codeText = codeText的情况才能使用它。

/*if*/ condition
     /*then*/? statement1
     /*else*/: statement2

所以,基本上这个如果构造:

if(condition){
    //statement1
}else{
    //statement2
}

可以写成:

condition 
    ? statement1
    : statement2;