【问题标题】:C# switch case with constant values as case conditionC# 以常量值作为 case 条件的 switch case
【发布时间】:2022-06-16 04:17:40
【问题描述】:

我正在使用 C# (8.0) switch 语句,如下所示:

var operation = 2;  

var result = operation switch  
{  
    1 => "Case 1",  
    2 => "Case 2",  
    3 => "Case 3",  
    4 => "Case 4",  
    _ => "No case available"  
};  

我想检查我们是否可以应用一些常量变量,其中包含一些值以匹配 case 条件 - 例如:

public static readonly string operation1 = "1";
public static readonly string operation2 = "2";

var result = operation switch  
{  
    operation1  => "Case 1",  
    operation2  => "Case 2",  
    _ => "No case available"  
};  

如果有更好的方法来处理这个问题,请告诉我部分

【问题讨论】:

  • 这很快就变得非常丑陋,而且可能不容易维护。我认为你的团队应该重新考虑整个事情。我将首先评估您是否真的需要工厂方法(这看起来就是这样)。然后,我会问,“我们真的需要泛型操作吗?应该将它们称为“操作 1”还是更具描述性的名称?如果这些是实际操作,您可能最好通过简单地将它们设为具有描述性名称的方法。最后,您应该阅读xyproblem.info
  • 枚举会比一堆字符串常量更清楚吗?

标签: c# switch-statement


【解决方案1】:

Constant expression可以直接通过constant patternswitch语句/表达式中使用:

const string operation1 = "1";
const string operation2 = "2";

var result = operation switch  
{  
    operation1  => "Case 1",  
    operation2  => "Case 2",  
    _ => "No case available"  
}; 

但如果它是一个变量而不是一个常量,那么可以使用 var patterncase guards 代替:

var operation1 = "1";
var operation2 = "2";

var result = operation switch  
{  
    var c1 when c1 == operation1  => "Case 1",  
    var c2 when c2 == operation2  => "Case 2",  
    _ => "No case available"  
}; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    相关资源
    最近更新 更多