switch-expression

Combine return and switch

非 Y 不嫁゛ 提交于 2019-12-04 09:14:11
问题 How can I combine return and switch case statements? I want something like return switch(a) { case 1:"lalala" case 2:"blalbla" case 3:"lolollo" default:"default" }; I know about this solution switch(a) { case 1: return "lalala"; case 2: return "blalbla"; case 3: return "lolollo"; default: return "default"; } But I want to only use the return operator. 回答1: switch and return can't combine that way, because switch is a statement , not an expression (i.e., it doesn't return a value). If you

Combine return and switch

偶尔善良 提交于 2019-12-03 03:19:13
How can I combine return and switch case statements? I want something like return switch(a) { case 1:"lalala" case 2:"blalbla" case 3:"lolollo" default:"default" }; I know about this solution switch(a) { case 1: return "lalala"; case 2: return "blalbla"; case 3: return "lolollo"; default: return "default"; } But I want to only use the return operator. switch and return can't combine that way, because switch is a statement , not an expression (i.e., it doesn't return a value). If you really want to use just a single return , you could make a Dictionary to map the switch variable to return

Multi-variable switch statement in C#

喜欢而已 提交于 2019-11-27 17:14:12
问题 I would like use a switch statement which takes several variables and looks like this: switch (intVal1, strVal2, boolVal3) { case 1, "hello", false: break; case 2, "world", false: break; case 2, "hello", false: etc .... } Is there any way to do something like this in C#? (I do not want to use nested switch statements for obvious reasons). 回答1: 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