Skip to content

NET新版代码技巧

约 147 字小于 1 分钟

NET

2026-02-08

switch守卫条件表达式

常规写法:

//打折计算
int CalcMoney(string product,int price)
{
	switch(product)
	{
		case "A":
			if(price>100) return price*0.9;
			if(price>1000) return price*0.8;
		case "B:
			if(price>200) return price*0.9;
			if(price>2000) return price*0.8;
		default:
			return product*0.99;
	}
}

使用switch表达式:

int CalcMoney(string product,int price) =>
	(product,price) switch
	{
		("A",>100) => price*0.9,
		("A",>1000) => price*0.8,
		("B",>200) => price*0.9,
		("B",>2000) => price*0.8,
		_=>_product*0.99
	};

工具类 静态using

var result = Helper.Funct(para);

Helper是静态类,可以使用静态using的写法:

using static Helper;
//直接调用
Funct(para);