在c#中可以从一个开关案例中指定一个返回值
本文关键字:一个 案例 返回值 开关 | 更新日期: 2023-09-27 18:03:03
我看过的所有c# switch语句的例子如下
var variable, result;
switch (variable) {
case 1: result = somevalue; break;
case 2: result = someothervalue; break;
}
然而,我想有一些像
var result = switch (variable) {
case 1: return <somevalue>;
case 2: return <someothervalue>;
}
可能吗?(也许我需要break
内部的情况下,但它是一个返回…)
在c# 8.0中可以使用新的switch语法:
var area = figure switch
{
Line _ => 0,
Rectangle r => r.Width * r.Height,
Circle c when c.Radius == 0 => throw new ThrowSomeException(c),
Circle c => Math.PI * c.Radius * c.Radius,
_ => throw new UnknownFigureException(figure)
};
您可以在这里阅读更多有关新功能的信息。
return <somevalue>
背后的基本思想是正确的,但switch
是一个控制语句所以它不return
是一个值。你必须让它成为这样一个方法:
dynamic SomeMethod(int variable)
{
switch(variable)
{
case 1: return "text";
case 2: return 5;
// Or manually return something out of switch scope
// because the method has to return something
default: return null;
}
}
void Test()
{
// Now you have a value assigned to an variable
// that comes from SomeMethod
// which is generated (selected) by switch
var result1 = SomeMethod(1); // string
var result2 = SomeMethod(2); // int
var result3 = SomeMethod(123); // null
}
在这种情况下,我还需要解释这一点:方法不能return
隐式类型(var
),因为编译器无法猜测return
类型是什么。但是你可以动态return
,现在类型会在运行时改变。此外,你不能在switch
中使用dynamic
,因为它需要一个可空类型。
如果你想让它简短(在方法中),可以用lambda:)创建一个匿名方法
var result =
(Func<int, dynamic>)
( (x) =>
{
switch(x)
{
case 1: return "text";
case 2: return 5;
default: return null;
}
} // Lambda
) // Func<int, dynamic> (takes int parameters, returns dynamic value)
(); // Call it and get return value to assign
但是我强烈建议你阅读一些文章,如语句,方法,类型…
考虑条件运算符
var result =
variable == 1? <somevalue>:
variable == 2? <someothervalue>:
<defaultvalue>;
如果希望根据某些输入返回值,并且希望使用开关作为可能的解决方案,可以考虑使用字典。
// populated with types and data that mean something
// to you.
private IDictionary<int, string> _lookupDictionary;
public string GetValue(int variable) {
return _lookupDictionary[variable];
// instead of
// switch (variable) {
// case 1:
// return <somevalue>;
// case 2:
// return <someothervalue>;
// ...
// case n-1:
// return <somethingelse>;
// case n:
// return <finalsomething>;
}
注意,开关本身不返回值。如果还想保存该返回值,那么只需使用字典的索引器执行查找,存储引用,然后返回。
private IDictionary<int, string> _lookupDictionary;
private KeyValuePair<int, string> _cache;
public string GetValue(int variable) {
if (!_lookupDictionary.ContainsKey(variable)) {
// throw an exception - or add - behavior dependent
// upon your need
}
if (_cache.Key == variable) {
return _cache.Value;
}
_cache = new KeyValuePair<int, string>(variable, _lookupDictionary[variable]);
return _cache.Value;
}