【发布时间】:2021-11-17 08:50:11
【问题描述】:
考虑以下几点:
var ch = 'i';
var str = "some item";
var result = ch switch
{
'a' => DoA("some", "parameters"),
_ when str.Contains("action a") => DoA("some", "parameters"),
'b' => DoB("some", "parameters"),
_ when str.Contains("action b") => DoB("some", "parameters"),
'c' => DoC(),
_ when str.Contains("action c") => DoC("some", "parameters"),
_ => new Exception("")
};
现在您可以在调用方法时看到重复,所以理想情况下我想要这样的东西:
var result = ch switch
{
'a' or (_ when str.Contains("action a")) => DoA("some", "parameters"),
'b' or (_ when str.Contains("action b")) => DoB("some", "parameters"),
'c' or (_ when str.Contains("action c")) => DoC("some", "parameters"),
_ => new Exception("")
};
但这会给我一个语法错误。
删除括号确实可以编译,但是逻辑等效于('a' or _) when str.Contains("action a")) => DoA("some", "parameters")
这不是我想要的。
有没有办法做到不重复?
【问题讨论】:
-
没有。当
when子句出现在模式之后,并且您试图将其折叠到模式本身中时
标签: c# pattern-matching c#-10.0