c#-切换语句Message.Contains
作者:互联网
是否可以使switch语句检查Message.Contains语句?
所以代替这个:
if (ex.Message.Contains("hnummer"))
{
MessageBox.Show("Deze laptop staat al in de lijst");
}
if (ex.Message.Contains("serienummmer"))
{
MessageBox.Show("Dit serienummer staat al in de lijst");
}
if (ex.Message.Contains("olcnummer"))
{
MessageBox.Show("Dit OLC nummer staat al in de lijst");
}
切换语句?
解决方法:
另一种方法是使用字典
//of course, the "staat al in de lijst" could be a constant, as we like DRY
var messageDictionary = new Dictionary<string, string>() {
{"hnummer", "Deze laptop staat al in de lijst"},
{"serienummmer", "Dit serienummer staat al in de lijst"}
}
然后是类似的内容(如果您希望每个“成功完成”的多个消息框包含测试,如代码所示).
foreach (var kvp in messageDictionary) {
if (ex.Message.Contains(kvp.Key))
Messagebox.Show(kvp.Value);
//break; if you wanna stop after first match.
}
或者如果您想测试所有“包含”但仅收到一条汇总消息
var res = string.Empty;
foreach (var kvp in messageDictionary) {
if (ex.Message.Contains(kvp.Key))
res +=kvp.Value;
}
MessageBox.Show(res);
还是“别那么做”的单一方式
MessageBox.Show(string.Join("\n", messageDictionary.Select(m => ex.Message.Contains(m.Key) ? m.Value : string.Empty)));
标签:if-statement,exception,switch-statement,c 来源: https://codeday.me/bug/20191030/1964113.html