我有這樣的代碼:困惑的:運營商
if (!codeText.StartsWith("<p>"))
{
codeText = string.Concat("<p>", codeText, "</p>");
}
我怎樣才能使它使用?:
操作?
我有這樣的代碼:困惑的:運營商
if (!codeText.StartsWith("<p>"))
{
codeText = string.Concat("<p>", codeText, "</p>");
}
我怎樣才能使它使用?:
操作?
codeText = codeText.StartsWith("<p>") ?
codeText :
string.Concat("<p>", codeText, "</p>");
感謝您的建議。 – Marianne
由於條件運算符需要一個else
條款,你需要告訴它使用原始值:
codeText = codeText.StartsWith("<p>") ? codeText : "<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
來使用它。
codeText = (!codeText.StartsWith("<p>")?string.Concat("<p>", codeText, "</p>"):codeText);
你可以做這樣的:
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 = condition?值,如果條件爲真:如果值條件爲假
/*if*/ condition
/*then*/? statement1
/*else*/: statement2
所以,基本上是這樣的,如果建設:
if(condition){
//statement1
}else{
//statement2
}
可以這樣寫:
condition
? statement1
: statement2;
你爲什麼要? – Howard
你爲什麼需要這個?你認爲這條線的表現更好嗎? –
這裏調用'string.Concat'沒有意義;你應該只使用'+'運算符。 – SLaks