我想在c#的开关语句中使用Contains(),但我不知道如何使用。如果你不明白我的话,我给你看一下代码,也许你会明白的。
我想工作的代码:
public void Read(string text)
{
switch (text.ToLower().Contains())
{
case "read":
MessageBox.Show(text);
break;
case "not":
MessageBox.Show(text);
break;
}
}
上面的代码是我尝试过的,但它不起作用。那么如何在switch语句中使用函数呢?我可以使用else if
s,但我想在switch语句中使用它。
如果只有2种情况,那么你应该总是使用它,但是如果你想要使用switch,你可以使用模式匹配。我认为你可能需要c# 7.0来做这个
public static void Read(string text)
{
switch (text)
{
case var read when text.ToLower().Contains("read"):
MessageBox.Show(text);
break;
case var nott when text.ToLower().Contains("not"):
MessageBox.Show(text);
break;
}
}
我不是说我的解决方案是完美的。我的回答是,这是可能的开关
public void Read(string text)
{
switch (text)
{
case string a when test.ToLower().Contains("read"):
MessageBox.Show(text);
break;
case string b when test.ToLower().Contains("not"):
MessageBox.Show(text);
break;
}
}
同样,答案在这里关于如何使用switch语句的string.Contains()方法。使用string.Contains()和switch()
Contains()
函数不能像这样在开关语句中使用,因为它将返回true
或false
,而开关语句适用于返回随机情况的变量,如1,2,3
,对于您的问题,最好使用'if else'代替。
正如我所看到的,两个case
都是相等的:无论文本包含"read"
或"not"
,我们都应该这样做:显示"text
">
我建议去掉switch
,只有一个if
:
using System.Linq; // to query with any
...
public void Read(string text) {
// public method arguments validation
if (null == text)
throw new ArgumentNullException(nameof(text));
string[] words = new string[] {"read", "not"};
// ToLower() is a bad practice:
// - it may occure that we don't have to process the entire text
// - StringComparison.OrdinalIgnoreCase is more readable
// - words doesn't have to lowercase words only
if (words.Any(word => text.Contains(word, StringComparison.OrdinalIgnoreCase)))
MessageBox.Show(text);
}