是否有任何方法可以使此代码更短?

时间:2016-09-27 09:05:13

标签: c#

if (richTextBox1.Text.Contains("Home") == false)
{               
    result_show.richTextBox1.Text += "Home in Home Menu is missing.";
}

if (richTextBox1.Text.Contains("Users") == false)
{               
    result_show.richTextBox1.Text += "Users in Home Menu is missing.";
}

if (richTextBox1.Text.Contains("Space") == false)
{               
    result_show.richTextBox1.Text += "Space in Home Menu is missing.";
}

https://stackoverflow.com/posts/39720620/ 或者您可以向下滚动以查看符合我需要的答案。感谢这一点。

4 个答案:

答案 0 :(得分:2)

string template = "{0} in Home Menu is missing.";
string[] keywords = new string[] { "home", "users", "space" };
for (int i = 0; i < keywords.Length; i++)
{
    result_show.richTextBox1.Text += richTextBox1.Text.Contains(keywords[i]) ?
             string.Empty : string.Format(template, keywords[i]);
}

如果您需要一些性能,请使用 StringBuilder

答案 1 :(得分:-1)

var list = new List<TextAndMessage>()
{
    new TextAndMessage {TextToCompare = "Home", Message = "Home in Home Menu is missing."},
    new TextAndMessage {TextToCompare = "Users", Message = "Home in Home Menu is missing."}
};

var sb = new StringBuilder();
foreach (var item in list)
{
    if (!richTextBox1.Text.Contains(item.TextToCompare))
    {
        sb.Append(item.Message);
    }
}
//Assigning at the end, as you might falsely check that the string is contained in textbox, that has come from one of the messages.
result_show.richTextBox1.Text = sb.ToString();

public class TextAndMessage
{
    public string TextToCompare { get; set; }
    public string Message { get; set; }
}

答案 2 :(得分:-1)

 Dictionary<string,string> Messages = new Dictionary<string,string> {"...."};

 var sb = new StringBuilder();

 Messages.ForEach(p=>
 {
    if(p.Key.Contains(richTextBox1.Text))
    {
     sb.Append(P.value);
    } 
 });

答案 3 :(得分:-3)

请使用以下模式:

Dictionary<string, string> wordsToCompare = new Dictionary<string, string>
{
    { "Home", "Home in Home Menu is missing." },
    { "Users", "Even another string here" },
    ...
};

private string GetSuffixString(string word)
{
    string resultString;
    wordsToCompare.TryGetValue(word, out resultString);
    return resultString;
} 

然后使用它:

StringBuilder builder = new StringBuilder(result_show.richTextBox1.Text);
builder.Append(this.GetSuffixString(richTextBox1.Text));
result_show.richTextBox1.Text = builder.ToString();