常量插值字符串C#10允许在常量字符串初始化中使用插值,如下conststringname="Oleg";conststringgreeting=$"你好,{name}。";Console.WriteLine(问候语);//输出:你好,Oleg。扩展的属性模式从C#10开始,您可以在适当的模式中引用嵌套的属性或字段,属性模式变得更易读且需要更少的花括号。Personperson=new(){Name="Oleg",Location=new(){Country="PL"}};if(personis{Name:"Oleg",Location.Country:"PL"}){控制台。WriteLine("是我!");}classPerson{publicstringName{get;放;}公共位置位置{得到;放;}}classLocation{publicstringCountry{get;放;}}如果Location为null,则模式不会被匹配并返回false。文件范围的命名空间C#10引入了一种声明命名空间的新方法——文件范围的命名空间、更少的大括号和更简洁的代码结构。命名空间FileScopedNamespace;类程序{staticvoidMain(string[]args){Console.WriteLine("HelloWorld!");}}GlobalUsingOne参考,全局通用使用GlobalusingSystem;全局使用System.Collections.Generic;全局使用System.Linq;全局使用System.Threading.Tasks;列表list=new(){1,2,3,4};intsum=list.Sum();控制台.WriteLine(sum);等待任务。延迟(1000);同一解构中的赋值和声明C#10允许在同一解构中赋值和声明。变量rgb=(255,100,30);//初始化和赋值intr;(r,intg,intb)=rgb;Console.WriteLine($"RGB:{r},{g},{b}");//Output:RGB:255,100,30Record类型重写ToString()时支持加密Productproduct=new(){Name="Bread"};Console.WriteLine(product.ToString());//输出:面包公共记录Product{publicstringName{get;在里面;}publicsealedoverridestringToString(){returnName;}}RecordStructC#10支持recordstructPersonme=new(){FirstName="Oleg",LastName="Kyrylchuk"};控制台.WriteLine(我);//输出:Person{FirstName=Oleg,LastName=Kyrylchuk}PersonotherPerson=mewith{FirstName="John"};Console.WriteLine(otherPerson);//输出:Person{FirstName=John,LastName=Kyrylchuk}PersonanotherMe=new(){FirstName="Oleg",LastName="Kyrylchuk"};Console.WriteLine(me==anotherMe);//输出:真实记录structPerson{publicstringFirstName{get;在里面;}publicstringLastName{get;在里面;}}recordstructProduct(stringName,decimalPrice);结构字段支持使用System进行初始化;Personperson=new(){Name="Oleg"};Console.WriteLine(person.Id+""+person.Name);//输出:0cc6caac-d061-4f46-9301-c7cc2a012e47OlegstructPerson{publicGuidId{get;在里面;}=Guid.NewGuid();公共字符串名称{得到;放;Lambda表达式Attributes支持C#9支持局部函数Attributes,C#10增加Lambda表达式Attributes支持动作a=[MyAttribute]()=>{};Actionb=[return:MyAttribute](x)=>{};动作c=[MyAttribute]([MyAttribute]x)=>{};classMyAttribute:Attribute{}LambdaTest()中的显式返回类型;varl1=string()=>string.Empty;varl2=int()=>0;varl3=staticvoid()=>{};voidTest(){varl4=T()=>默认值;应用于方法的AsyncMethodBuilder特性从C#7开始,您只能将AsyncMethodBuilder特性应用于类型,在C#10中,您还可以将该特性应用于单个方法。使用System.Runtime.CompilerServices;classExample{[AsyncMethodBuilder(typeof(AsyncVoidMethodBuilder))]publicvoidExampleMethod(){}}结构中的表达式C#10支持将with表达式与结构Productpotato=new(){Name="Potato",Category="蔬菜”};Console.WriteLine($"{potato.Name}{potato.Category}");//输出:马铃薯蔬菜产品tomato=potatowith{Name="Tomato"};Console.WriteLine($"{tomato.Name}{tomato.Category}");//输出:TomatoVegetablestructProduct{publicstringName{get;放;}公共字符串类别{得到;放;}}类型中的匿名表达式C#10支持使用with匿名类型的表达式varpotato=new{Name="Potato",Category="Vegetable"};Console.WriteLine($"{potato.Name}{potato.Category}");//输出:土豆蔬菜varonion=potatowith{Name="Onion"};Console.WriteLine($"{onion.Name}{onion.Category}");//输出:洋葱蔬菜本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: