1、扩展方法
using System;
class Example
{
static void Main(string[] args)
{
int a = 5;
int b = -1;
a.IsNegativeNum();//返回false
b.IsNegativeNum();//返回true
}
}
//注意:扩展类必须为静态
static class ExtInt
{
public static bool IsNegativeNum(this int num)
{
return num < 0;
}
}
2、巧用goto语句
enum ExitEnum { SaveAndQuit, JustQuit }
class DataManager
{
public static void Save() { ... }
public static void Quit() { ... }
}
//...
ExitEnum choice = ...;
switch (choice)
{
case ExitEnum.SaveAndQuit:
DataManager.Save();
goto case ExitEnum.JustQuit;
break;
case ExitEnum.JustQuit:
DataManager.Quit();
break;
}
3、返回switch语句
class Example
{
public static string GetComment(int score) => score switch
{
>= 0 and <= 50 => "Bad",//分数大于等于0且小于等于50时返回bad
_ => "Good"//不符合以上条件,返回good
}//除了and,你也可以使用is,not,or等逻辑关键字来进行条件判断
}