我使用 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 语句中的值,我们在一个地方维护常量,并在不同部分的项目中引用它们
Constant expression可以直接通过constant pattern在switch
语句 / 表达式中使用:
const string operation1 = "1";
const string operation2 = "2";
var result = operation switch
{
operation1 => "Case 1",
operation2 => "Case 2",
_ => "No case available"
};
但是,如果它是一个变量而不是一个常量,那么var pattern与case 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"
};
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(38条)