我如何结合return
和switch case
声明?
我想要类似的东西
return switch(a)
{
case 1:"lalala"
case 2:"blalbla"
case 3:"lolollo"
default:"default"
};
我知道这个解决方案
switch(a)
{
case 1: return "lalala";
case 2: return "blalbla";
case 3: return "lolollo";
default: return "default";
}
但我想只使用return
运算符。
switch
和return
不能以这种方式结合,因为switch
是一个声明,而不是表达式(即,它不返回值)。
如果你真的想只使用一个return
,你可以创建一个Dictionary来将switch变量映射到返回值:
var map = new Dictionary<int, string>()
{
{1, "lala"},
{2, "lolo"},
{3, "haha"},
};
string output;
return map.TryGetValue(a, out output) ? output : "default";
public String doStaff(int a) {
switch(a)
{
case 1: return "lalala"
case 2: return "blalbla"
case 3: return "lolollo"
default: return "default"
};
}
我们可以有一个用例,我们可能需要从switch中写入的条件返回值;让我们说:
public void SomeMethod(SomeType enumType)
{
switch (enumType)
{
case a:
if (condition)
{
if (condition1 && condition2)
{
return true;
}
}
return false;
//break; break is actually not be required here if return used before break
case b:
if (condition)
{
if (condition3 && condition4)
{
return true;
}
}
return false;
// break;
default:
return false;
//break;
}
Public enum SomeType
{
a,
b,
c,
d
}
我相信这个解决方案是最直接的解决方案,你绝对应该使用它:
switch(a) {
case 1: return "lalala";
case 2: return "blabla";
case 3: return "lololo";
default: return "default";
}
但是,既然你要求一个return
,你可以使用这个流利的小班:
public class Switch<TElement, TResult> {
TElement _element;
TElement _currentCase;
IDictionary<TElement, TResult> _map = new Dictionary<TElement, TResult>();
public Switch(TElement element) { _element = element; }
public Switch<TElement, TResult> Case(TElement element) {
_currentCase = element;
return this;
}
public Switch<TElement, TResult> Then(TResult result) {
_map.Add(_currentCase, result);
return this;
}
public TResult Default(TResult defaultResult) {
TResult result;
if (_map.TryGetValue(_element, out result)) {
return result;
}
return defaultResult;
}
}
要创建这样的代码:
return new Switch<int, string>(a)
.Case(1).Then("lalala")
.Case(2).Then("blabla")
.Case(3).Then("lololo")
.Default("default");
不幸的是,编译器无法推断类型参数,感觉有点笨拙。 Default
将触发“switch”的评估,并且必须是链中的最后一个方法调用。请注意,您始终需要一个默认值,因为您已将switch
转换为表达式。
更新:您可以解决类型推断问题并驱动用户使用以下代码执行正确的操作:
public static class Switch {
public static SwitchBuilder<TElement>.CaseBuilder On<TElement>(TElement element) {
return new SwitchBuilder<TElement>(element).Start();
}
public class SwitchBuilder<TElement> {
TElement _element;
TElement _firstCase;
internal SwitchBuilder(TElement element) { _element = element; }
internal CaseBuilder Start() {
return new CaseBuilder() { Switch = this };
}
private ThenBuilder Case(TElement element) {
_firstCase = element;
return new ThenBuilder() { Switch = this };
}
private SwitchBuilder<TElement, TResult>.CaseBuilder Then<TResult>(TResult result) {
return new SwitchBuilder<TElement, TResult>(
_element,
_firstCase,
result).Start();
}
public class CaseBuilder {
internal SwitchBuilder<TElement> Switch { get; set; }
public ThenBuilder Case(TElement element) {
return Switch.Case(element);
}
}
public class ThenBuilder {
internal SwitchBuilder<TElement> Switch { get; set; }
public SwitchBuilder<TElement, TResult>.CaseBuilder Then<TResult>(TResult result) {
return Switch.Then(result);
}
}
}
public class SwitchBuilder<TElement, TResult> {
TElement _element;
TElement _currentCase;
IDictionary<TElement, TResult> _map = new Dictionary<TElement, TResult>();
internal SwitchBuilder(TElement element, TElement firstCase, TResult firstResult) {
_element = element;
_map.Add(firstCase, firstResult);
}
internal CaseBuilder Start() {
return new CaseBuilder() { Switch = this };
}
private ThenBuilder Case(TElement element) {
_currentCase = element;
return new ThenBuilder() { Switch = this };
}
private CaseBuilder Then(TResult result) {
_map.Add(_currentCase, result);
return new CaseBuilder() { Switch = this };
}
private TResult Default(TResult defaultResult) {
TResult result;
if (_map.TryGetValue(_element, out result)) {
return result;
}
return defaultResult;
}
public class CaseBuilder {
internal SwitchBuilder<TElement, TResult> Switch { get; set; }
public ThenBuilder Case(TElement element) {
return Switch.Case(element);
}
public TResult Default(TResult defaultResult) {
return Switch.Default(defaultResult);
}
}
public class ThenBuilder {
internal SwitchBuilder<TElement, TResult> Switch { get; set; }
public CaseBuilder Then(TResult result) {
return Switch.Then(result);
}
}
}
}
结果是这个漂亮,类型安全,流畅的界面;在每一步,您只能选择正确的方法(例如Then
之后的Case
):
return Switch.On(a)
.Case(1).Then("lalala")
.Case(2).Then("blabla")
.Case(3).Then("lololo")
.Default("default");
我通常这样做:
var result = null;
switch(a)
{
case 1:
result = "lalala";
break;
case 2:
result = "blalbla";
break;
case 3:
result = "lolollo";
break;
default:
result = "default";
break;
};
return result;
switch(a)
{
case 1: return "lalala";
case 2: return "blalbla";
case 3: return "lolollo";
default: return "default";
}
这是我能想到的最接近的:
return a==1 ? "lalala"
: a==2 ? "blalbla"
: a==3 ? "lolollo"
: "default";
我的mapping solution看起来像Jordão的解决方案,但它更灵活,更短。
return a
.Map(1,"lalala")
.Map(2,"blabla")
.Map(3,"lololo")
.Else(string.Empty);
两个参数也可以是一个函数:
return a
.Map(x => x <= 0, "lalala")
.Map(2, "blabla")
.Map(x => x >= 3, x => "lololo" + x.ToString()); // lololo3 etc.
我已经创建了一个Nuget包(FluentSwitch),可以做你想要的。所以你可以做到以下几点:
var result = myValue.Switch()
.When(1, "lalala")
.When(2, "blalbla")
.When(3, "lolollo")
.Else("default")
.Value();
如果要切换到返回值,可以使用委托:
int a = 2;
string result = new Func<string>(delegate ()
{
switch (a)
{
case 1: return "lalala";
case 2: return "blalbla";
case 3: return "lolollo";
default: return "default";
}
})();
要么:
int a = 2;
string result = new Func<int,string>(delegate (int i)
{
switch (i)
{
case 1: return "lalala";
case 2: return "blalbla";
case 3: return "lolollo";
default: return "default";
}
})(a);
或者只使用lambda:
int a = 2;
string result = new Func<int,string>((int i) =>
{
switch (i)
{
case 1: return "lalala";
case 2: return "blalbla";
case 3: return "lolollo";
default: return "default";
}
})(a);
使用新的C# 8
,你可以结合使用return
和switch
。新的switch
非常可爱。
public static RGBColor FromRainbow(Rainbow colorBand) =>
colorBand switch
{
Rainbow.Red => new RGBColor(0xFF, 0x00, 0x00),
Rainbow.Orange => new RGBColor(0xFF, 0x7F, 0x00),
Rainbow.Yellow => new RGBColor(0xFF, 0xFF, 0x00),
Rainbow.Green => new RGBColor(0x00, 0xFF, 0x00),
Rainbow.Blue => new RGBColor(0x00, 0x00, 0xFF),
Rainbow.Indigo => new RGBColor(0x4B, 0x00, 0x82),
Rainbow.Violet => new RGBColor(0x94, 0x00, 0xD3),
_ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand)),
};
等效的旧开关如下。
public static RGBColor FromRainbowClassic(Rainbow colorBand)
{
switch (colorBand)
{
case Rainbow.Red:
return new RGBColor(0xFF, 0x00, 0x00);
case Rainbow.Orange:
return new RGBColor(0xFF, 0x7F, 0x00);
case Rainbow.Yellow:
return new RGBColor(0xFF, 0xFF, 0x00);
case Rainbow.Green:
return new RGBColor(0x00, 0xFF, 0x00);
case Rainbow.Blue:
return new RGBColor(0x00, 0x00, 0xFF);
case Rainbow.Indigo:
return new RGBColor(0x4B, 0x00, 0x82);
case Rainbow.Violet:
return new RGBColor(0x94, 0x00, 0xD3);
default:
throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand));
};
}
你可以读一下这个功能here。