Confused about the ?: operator
I h开发者_如何学Cave this code:
if (!codeText.StartsWith("<p>"))
{
codeText = string.Concat("<p>", codeText, "</p>");
}
How can I make it use the ?:
operator?
Since the conditional operator needs an else
clause, you need to tell it to use the original value:
codeText = codeText.StartsWith("<p>") ? codeText : "<p>" + codeText + "</p>";
However, there is no point in doing this; it's just more confusing.
codeText = codeText.StartsWith("<p>") ?
codeText :
string.Concat("<p>", codeText, "</p>");
In this case it doesn't make much sense to use the ternary operator. I would just stick with the if statement you have now. Typically you would use the ternary operator in an assignment statement or somewhere that you can't use a typical if statement.
However, if you really want to, you could do it like this.
codeText = !codeText.StartsWith("<p>") ? string.Concat("<p>", codeText, "</p>") : codeText;
Here's the MSDN page for the ternary operator. http://msdn.microsoft.com/en-US/library/ty67wk28%28v=VS.80%29.aspx
variable = condition ? value if condition is true : value if condition is false
codeText = (!codeText.StartsWith("<p>")?string.Concat("<p>", codeText, "</p>"):codeText);
You could do it like this:
codeText = codeText.StartsWith("<p>")
? codetext
: string.Concat("<p>", codeText, "</p>");
But I'm not sure why would you do that.
Like this:
codeText = codeText.StartsWith("<p>") ? codeText : string.Concat("<p>", codeText, "</p>");
If it's fairly long, I usually write it across multiple lines like this:
codeText = codeText.StartsWith("<p>")
? codeText
: string.Concat("<p>", codeText, "</p>");
although I have to admit, I don't see the benefit to using the ?: operator here, given that you don't have an else case, you're having to add one that does codeText = codeText
to use it.
/*if*/ condition
/*then*/? statement1
/*else*/: statement2
so, basically this if construction:
if(condition){
//statement1
}else{
//statement2
}
can be written like :
condition
? statement1
: statement2;
精彩评论