1、默认接口方法
之前接口中不能声明方法体,成员也不能有Public修饰符
现在,可以在接口中声明方法体,和抽象类越来越像
interface CustomInterface
{
public void Show();
public void ShowInfo()//该方法有方法体
{
Console.WriteLine("this is ShowInfo");
}
}
//调用
CustomInterface interface1 = new CustomClass();
interface1.ShowInfo();
2、switch
之前写法
public static string WeekToStringSwitch(WeekInfo week)
{
switch (week)
{
case WeekInfo.Monday:
return "周一";
case WeekInfo.Tuesday:
return "周二";
case WeekInfo.Wednesday:
return "周三";
case WeekInfo.Thursday:
return "周四";
case WeekInfo.Friday:
return "周五";
case WeekInfo.Saturday:
return "周六";
case WeekInfo.Sunday:
return "周七";
default:
throw new NotImplementedException("枚举不存在");
}
}
现在可以这样:
public static string WeekToString(WeekInfo week) => week switch //此处是Lambda表达式
{
WeekInfo.Monday => "周一",
WeekInfo.Tuesday => "周二",
WeekInfo.Wednesday => "周三",
WeekInfo.Thursday => "周四",
WeekInfo.Friday => "周五",
WeekInfo.Saturday => "周六",
WeekInfo.Sunday => "周七",
_ => throw new NotImplementedException("枚举不存在"),
};
3、属性模式
定义如下PropertyPattern类,类中两个属性,
public class PropertyPattern
{
public string ProductName { get; set; }
public double Price { get; set; }
}
//实例化PropertyPattern类,将两个属性初始化
PropertyPattern product = new PropertyPattern()
{
ProductName = "aa",
Price = 5
};
C#8.0可以直接将属性应用于Switch结构
public static double PropertyPatternShow(PropertyPattern pattern) => pattern switch
{
{ ProductName: "aa" } => pattern.Price * 0.5,
{ Price: 234 } => pattern.Price * 0.5,
_ => throw new NotImplementedException(),
};
4、元组模式
string strResult = RockPaperScissors("aa", "bb");
public static string RockPaperScissors(string first, string second)
=> (first, second) switch
{
("aa", "bb") => $"{first}-{second}",
("aa", "cc") => $"{first}-{second}",
("aa", "dd") => $"{first}-{second}",
(_, _) => "不匹配"
};
5、静态本地函数
类似于C#7.0中新增的本地函数语法,函数中调用另一个声明在本函数体中的方法,只不过C#8.0中针对的是静态函数
static int M()
{
int y = 5;
int x = 7;
return Add(x, y);
static int Add(int left, int right) => left + right;
}
6、using 声明
using 声明是前面带 using
关键字的变量声明。 它指示编译器声明的变量应在封闭范围的末尾进行处理。 以下面编写文本文件的代码为例:
之前的写法:
static int WriteLinesToFile(IEnumerable<string> lines)
{
using (var file = new System.IO.StreamWriter("WriteLines2.txt"))
{
int skippedLines = 0;
foreach (string line in lines)
{
...
}
return skippedLines;
} // file is disposed here
}
更新后:
static int WriteLinesToFile(IEnumerable<string> lines)
{
using var file = new System.IO.StreamWriter("WriteLines2.txt");
int skippedLines = 0;
foreach (string line in lines)
{
.......
}
return skippedLines;
// file is disposed here
}