我们在写Switch的时候,有些情况每个case都只有一个语句且逻辑相同,这时我们就可以使用简化的写法。
废话不多说,直接上实例代码
简化前
if (!string.IsNullOrEmpty(request.TypeReq))
{
switch (request.TypeReq)
{
case "1":
whereSql += " and BomCode IS NOT NULL ";
break;
case "2":
whereSql += " and BomCode IS NULL ";
break;
default:
break;
}
}
简化后
if (!string.IsNullOrEmpty(request.TypeReq))
{
whereSql += request.TypeReq switch
{
"1" => " and BomCode IS NOT NULL ",
"2" => " and BomCode IS NULL ",
_ => "",
};
}