在字符串比较中有C#开关的要求。
string result = getResponse();
switch (result)
{
case "S0": ret = "true";
break;
case "S1": ret = "fail";
break;
// ? can be any digit number, ex, M:0, M:100, M:1000
case "M:?": ret = result;
break;
default: ret = "wrong";
break;
}
如何在“M:?”中创建switch语句情况?
答案 0 :(得分:3)
如果您使用的是C#7,则可以使用switch pattern matching.
string ret = string.Empty;
string result = getResponse();
switch (result)
{
case "S0":
ret = "true";
break;
case "S1":
ret = "fail";
break;
case var val when new Regex(@"^M:\d+").IsMatch(val):
ret = val;
break;
default:
ret = "wrong";
break;
}
正如@KingKing在问题中评论说许多开发人员没有使用C#7的奢侈品,那时你可以使用以下代码:
string result = getResponse();
switch (Regex.IsMatch(result, @"^M:\d+") ? "M:XXX" : result)
{
case "S0":
ret = "true";
break;
case "S1":
ret = "fail";
break;
case "M:XXX": // make it unique so that it will not collide with other case statement and update this value in ternary condition accordingly
ret = result;
break;
default:
ret = "wrong";
break;
}
答案 1 :(得分:1)
尝试使用模式匹配: -
public string Convert(string result)
{
switch (result)
{
case "S0": return "true";
case "S1": return "fail";
case var m when Regex.IsMatch(m, @"^M:\d+$"): return m;
default: return "wrong";
}
}
如果您使用较旧的C#而没有模式匹配,请将您的子句移到开关
之前 public string Convert(string result)
{
if(Regex.IsMatch(result, @"^M:\d+$")) return result;
switch (result)
{
case "S0": return "true";
case "S1": return "fail";
default: return "wrong";
}
答案 2 :(得分:1)
另一种选择,而不是使用开关模式匹配,是使用if语句处理默认块中更复杂的情况
string ret = string.Empty;
string result = getResponse();
switch (result)
{
case "S0":
ret = "true";
break;
case "S1":
ret = "fail";
break;
default:
Regex rgx = new Regex(@"^M:\d+");
if (rgx.IsMatch(result))
{
ret = result;
}
else {
ret = "wrong";
}
break;
}
答案 3 :(得分:0)
如何使用LINQ:
var switches = new Func<string, string>[]
{
x => x == "S0" ? "true" : null,
x => x == "S1" ? "fail" : null,
x =>
{
var match = Regex.Match(x, @"^M:(\d+)");
if (match.Success)
return match.Groups[1].Captures[0].Value;
return null;
},
x => "wrong",
};
string result = "M:47";
string ret = switches.Select(s => s(result)).Where(r => r != null).First();
这为"47"
提供了ret
。