簡體   English   中英

如何使用帶有 String.Contains 的 switch case?

[英]How to use switch case with String.Contains?

我想在下面的代碼中使用switch case 這可能嗎?如果可以,怎么做?

private IEnumerable<string> GetRowValues(DataRow dr)
{
    foreach (DataColumn col in DataResult.Columns)
        yield return replaceSpecialChar(dr[col].ToString());
}

private string replaceSpecialChar(string text)
{
    if (text.Contains("<"))
    {
        text = text.Replace("<", "&lt;");
    }
    else if (text.Contains(">"))
    {
        text = text.Replace(">", "&gt;");
    }
    else if (text.Contains("<=")){
        text = text.Replace("<=", "&le;");
    }
    else if (text.Contains(">="))
    {
        text = text.Replace(">=","&ge;");
    }
    return text;
}

快速的答案是,你不能使用switch來做你想做的事,你也不應該嘗試。 在當前形式中,如果您的字符串包含多個符號,則只有它匹配的第一個將被替換。

您還需要注意執行這些操作的順序,因為<=最終會成為&lt= 您還缺少"&lt""&gt"的尾隨分號

您應該做的只是將多個調用鏈接到.Replace()

private string replaceSpecialChar(string text)
{
    return text
        .Replace("<=", "&le;")
        .Replace(">=", "&ge;")
        .Replace("<", "&lt;")
        .Replace(">", "&gt;");
}

正如一些人已經說過的那樣:您不能將其更改為開關,因為您不能對案例使用函數,但較新的 C# 版本的一些簡單條件除外。

除此之外,您的代碼看起來像您想用 html 代碼替換替換所有給定的特殊字符。 您的代碼目前僅替換符合您的一個條件的第一個特殊字符,而不是全部。

如果您想用 html 代碼替換所有給定字符,則不需要 if/else if 部件。 只需使用它:

return text.Replace("<=", "&le;")
    .Replace(">=", "&ge;")
    .Replace("<", "&lt;")
    .Replace(">", "&gt;");

*編輯似乎 phuzi 更快,並且還提到了替換角色的順序;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM