常量的内插字符串 C10允许使用在常量字符串初始化中使用插值,如下conststringnameOconststringgreeting34;Hello,{name}。;Console。WriteLine(greeting);Output:Hello,Oleg。 扩展属性模式 从C10开始,您可以在适当的模式中引用嵌套的属性或字段,属性模式变得更具可读性并且需要更少的大括号。Personpersonnew(){NameOleg,Locationnew(){CountryPL}};if(personis{Name:Oleg,Location。Country:PL}){Console。WriteLine(Itsme!);}classPerson{publicstringName{}publicLocationLocation{}}classLocation{publicstringCountry{}} 如果Location为null,则不会匹配模式并返回false。 文件范围的命名空间 C10引入了一种新的命名空间声明方式文件范围的命名空间,减少一个大括号,代码结构更简洁。namespaceFileScopedNclassProgram{staticvoidMain(string〔〕args){Console。WriteLine(HelloWorld!);}} 全局Using 一次引用,全局通用globalusingSglobalusingSystem。Collections。GglobalusingSystem。LglobalusingSystem。Threading。TListintlistnew(){1,2,3,4};intsumlist。Sum();Console。WriteLine(sum);awaitTask。Delay(1000); 同一个解构中的赋值和声明 C10可以在同一个解构中进行赋值和声明。varrgb(255,100,30);I(r,intg,intb)Console。WriteLine(34;RGB:{r},{g},{b});Output:RGB:255,100,30 Record类型重写ToString()时支持密封Productproductnew(){NameBread};Console。WriteLine(product。ToString());Output:BreadpublicrecordProduct{publicstringName{}publicsealedoverridestringToString(){returnN}} RecordStruct C10支持recordstructPersonmenew(){FirstNameOleg,LastNameKyrylchuk};Console。WriteLine(me);Output:Person{FirstNameOleg,LastNameKyrylchuk}PersonotherPersonmewith{FirstNameJohn};Console。WriteLine(otherPerson);Output:Person{FirstNameJohn,LastNameKyrylchuk}PersonanotherMenew(){FirstNameOleg,LastNameKyrylchuk};Console。WriteLine(meanotherMe);Output:TruerecordstructPerson{publicstringFirstName{}publicstringLastName{}}recordstructProduct(stringName,decimalPrice); Struct字段支持初始化usingSPersonpersonnew(){NameOleg};Console。WriteLine(person。Idperson。Name);Output:0cc6caacd0614f469301c7cc2a012e47OlegstructPerson{publicGuidId{}Guid。NewGuid();publicstringName{}} Lambda表达式的Attributes支持 C9支持本地函数的Attributes,C10添加了Lambda表达式的Attributes支持。Actiona〔MyAttribute〕(){};Actionintb〔return:MyAttribute〕(x){};Actionintc〔MyAttribute〕(〔MyAttribute〕x){};classMyAttribute:Attribute{} Lambda中的显式返回类型Testint();varl1string()string。Evarl2int()0;varl3staticvoid(){};voidTestT(){varl4T()} 应用于方法的AsyncMethodBuilder特性 从C7开始,您只能将AsyncMethodBuilder特性应用于类型,在C10中,您还可以将该特性应用于单个方法。usingSystem。Runtime。CompilerSclassExample{〔AsyncMethodBuilder(typeof(AsyncVoidMethodBuilder))〕publicvoidExampleMethod(){}} 结构体中的表达式 C10支持将with表达式和struct一起使用Productpotatonew(){NamePotato,CategoryVegetable};Console。WriteLine(34;{potato。Name}{potato。Category});Output:PotatoVegetableProducttomatopotatowith{NameTomato};Console。WriteLine(34;{tomato。Name}{tomato。Category});Output:TomatoVegetablestructProduct{publicstringName{}publicstringCategory{}} 匿名类型中的表达式 C10支持将with表达式和匿名类型一起使用varpotatonew{NamePotato,CategoryVegetable};Console。WriteLine(34;{potato。Name}{potato。Category});Output:PotatoVegetablevaronionpotatowith{NameOnion};Console。WriteLine(34;{onion。Name}{onion。Category});Output:OnionVegetable 文章来源于全球技术精选,作者OlegKyrylchuk