C#8.0新语法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(""))
{
int skippedLines = 0;
foreach (string line in lines)
writeline和writelines{
...
}
return skippedLines;
} // file is disposed here
}
更新后:
static int WriteLinesToFile(IEnumerable<string> lines)
{
using var file = new System.IO.StreamWriter("");
int skippedLines = 0;
foreach (string line in lines)
{
.......
}
return skippedLines;
// file is disposed here
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。