C# 中的多变量 switch 语句
我想使用一个带有多个变量的 switch 语句,如下所示:
switch (intVal1, strVal2, boolVal3)
{
case 1, "hello", false:
break;
case 2, "world", false:
break;
case 2, "hello", false:
etc ....
}
Is有什么方法可以在 C# 中执行类似的操作吗? (出于显而易见的原因,我不想使用嵌套的 switch 语句)。
.net 开发团队通过实施这种恐惧来回答了这个问题: C# 中的多变量 switch 语句
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
是的。从 .NET 4.7 和 C# 8 开始支持它。语法几乎与您提到的相同,但带有一些括号(请参阅 元组模式)。
如果您想切换并返回一个值,可以使用 switch“表达式语法”。这是一个例子;请注意默认情况下使用
_
:下面是来自上面链接的 MSDN 文章的更具说明性的示例(石头、剪刀、布游戏):
Yes. It's supported as of .NET 4.7 and C# 8. The syntax is nearly what you mentioned, but with some parenthesis (see tuple patterns).
If you want to switch and return a value there's a switch "expression syntax". Here is an example; note the use of
_
for the default case:Here is a more illustrative example (a rock, paper, scissors game) from the MSDN article linked above:
您可以在 C# 7 及更高版本中使用
when
关键字:You can do this in C# 7 and higher with the
when
keyword:C# 中没有内置功能可以执行此操作,而且我不知道有任何库可以执行此操作。
这是一种替代方法,使用 Tuple 和扩展方法:
这基本上只是提供一种方便的语法来检查多个值 - 并使用多个 if 而不是一个
开关
。There is (was) no built-in functionality to do this in C#, and I don't know of any library to do this.
Here is an alternative approach, using
Tuple
and extension methods:This is basically doing nothing more than providing a convenient syntax to check for multiple values - and using multiple
if
s instead of aswitch
.让我们换个角度来看这个问题。如果您有:
int
、bool
、string
等)然后您可以使用查找表
代码示例:
如果您需要为每种情况实际执行一个函数或方法,那么您可以使用
Action
或Func
结果类型(字典值)代码> 代替。请注意,我在这里使用
Tuple
因为它已经内置了所有哈希代码逻辑。该语法在 C# 中有点尴尬,但如果您愿意,您可以实现您自己的查找类,只需覆盖Equals
和GetHashCode
即可。Let's look at this another way. If you have:
int
,bool
,string
, etc.)Then you can use a look-up table instead, which has a similar execution speed to the
switch
statement but not quite as efficient (since it needs to calculate hashes). Still, it's probably good enough. And it gives you the opportunity to name cases, to make this combinatorial explosion slightly less confusing and unmaintainable.A code example:
If you need to actually execute a function or method for each case then you can use a result type (dictionary value) of
Action<T>
orFunc<T>
instead.Note that I'm using
Tuple<T1,T2,T3>
here because it already has all of the hash code logic built in. The syntax is a little awkward in C# but if you want, you can implement your own lookup class and just overrideEquals
andGetHashCode
.我对此的看法简直是疯狂:
My downright crazy take on this:
您可以转换为字符串:
我认为出现的问题是是否有更好的方法来定义逻辑。例如,假设您想找出谁认识超人。我们可以这样进行检查:
但是当你找到另一个叫克拉克·肯特的人时会发生什么?你真的不能有一些其他值来确定这个逻辑,即 bool KnowsSuperman 吗?
这个想法是, switch 语句用于根据一组选择来确定逻辑。如果您尝试关闭多个值,那么逻辑可能会变得非常难以维护。
另一个例子是,如果您需要将人们分为几个组,并根据他们所在的组执行一些逻辑。您可以编写代码来表示,如果您是 Bob、Jeff、Jim 或 Sally,那么您就是在 A 组中,但是如果您需要将其他人添加到 A 组中怎么办?你必须更改代码。相反,您可以创建一个名为 Group 的额外属性,它可以是枚举或字符串,您可以使用它来指定某人所在的组。
You could convert to a string:
I think the question that comes to play, though is whether or not there's a better way of defining the logic. For instance, let's say you're trying to figure out who knows superman. We could do the check like this:
But what happens when you get some other guy named Clark Kent? Really couldn't you have some other value that you determine this logic based on, ie bool KnowsSuperman?
The idea being, a switch statement is used to determine logic based off a single set of choices. If there are multiple values you're trying to switch off of, then the logic could get insanely difficult to maintain down the line.
Another example would be if you need to group people into several groups and perform some logic depending on the group they're in. You could code it up to say, if you're Bob, Jeff, Jim, or Sally, you're in group A, but what if you need to add someone else to group A? You'd have to change the code. Instead, you could create an extra property called Group, which could be an enum or string, which you could use to specify which group someone is in.
2018 年更新。从 C#7.0 开始,Microsoft 为开关引入了“when”子句,使得可以有效地使用附加条件扩展开关情况。
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch#the-case-statement-and-the-when-clause
Update for 2018. As of C#7.0 Microsoft introduced the "when" clause for switches making it effectively possible to extend switch cases with additional conditions.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch#the-case-statement-and-the-when-clause
我不确定这出现在哪个 C# 版本中,但你可以这样做:
I'm not sure which C# version this appeared it but you can do this:
根据 C# 语言规范,
switch
语句表达式必须解析为 sbyte、byte、sbyte、byte、short、ushort、int、uint、long、ulong、char、string 或枚举类型。这意味着您无法打开Tuple
或其他高阶类型。假设有空间,您可以尝试将这些值打包在一起。例如,假设每个整数都保证在 0..9 范围内。
Per the C# language specification, the
switch
statement expression must resolve to one of sbyte, byte, sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type. This means you cannot switch onTuple
or other higher-order types.You could try to pack the values together, assuming there is room. For example, suppose each of the integers is guaranteed to be in the range 0..9.
我用列表或数组做这种事情。如果您可以枚举可能的条件(如果您想要进行多值切换,那么显然可以),然后使用多部分键和
Action
或构建一个查找表>Func
作为值。一个简单的版本将使用
Dictionary
:以及您的字典:
然后您可以在启动时填充字典,然后查找就变得很简单:
需要设置一些代码,但它非常简单执行速度快。
I do this kind of thing with lists or arrays. If you can enumerate the possible conditions (which you obviously can if you're wanting to do a multi-value switch), then build a lookup table with a multi-part key and an
Action
orFunc<T>
as the value.A simple version would use a
Dictionary
:And your dictionary:
You can then populate the dictionary at startup, and then a lookup becomes a simple matter of:
It's a bit of code to set up, but it's very quick in execution.
据我所知,你不能在 C# 中做到这一点。
但您可以从 MSDN 中执行此操作:
以下示例显示,对于空 case 标签,允许从一个 case 标签跌落到另一个 case 标签:
You cannot do that in C# as far as I know.
But you can do this from MSDN:
The following sample shows that fall through from one case label to another is allowed for empty case labels: