C语言case:以常量值作为case条件的C# 开关情况

关于C语言case的问题,在c# select case中经常遇到, 我使用 C #(8.0)开关语句如下所示:

我使用 C #(8.0)开关语句如下所示:

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

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

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"  
};  

请让我知道是否有更好的方法来处理这个问题,我不想按照标准硬编码 switch 语句中的值,我们在一个地方维护常量,并在不同部分的项目中引用它们

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"  
}; 

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(199)
Ca talent:linkedin人才洞察 api
上一篇
Jpeg压缩:jpeg压缩比(compression ratio image)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(38条)