C# 7.0 Expression Bodied Members

文章推薦指數: 80 %
投票人數:10人

Lambda expressions can be written in short form without curly brackets when the statement consists of a single line. Skiptocontent Menu PrimaryNavigation SubscribetoBlogviaEmail Enteryouremailaddresstosubscribetothisblogandreceivenotificationsofnewpostsbyemail. Join2,287otherfollowers EmailAddress: Subscribe FollowMe RecentPosts CreatingaWindowsServicewith.NET6 UpgradinganASP.NETCoreWebAPIProjectto.NET6 C#NullableFeaturesthruthetimes UsingAzureActiveDirectoryB2Cwith.NET TemporalTableswithEFCore6 PopularTags.NETCore ASP.NETCore Azure Basta C# C#7 C#7.0 Conference CSharp CSharp8 dependencyinjection DI dotnet dotnetcore EFCore ProfessionalC# UniversalWindowsPlatform UWP WPF XAMLBestbooks FollowmeonTwitterMyTweets C#6introducedexpressionbodiedmemberswithmethodsandproperties.ThisfeaturehasbeenenhancedwithC#7.0toallowexpressionbodiedmemberswithconstructors,destructors,andalsopropertyaccessors.ThisarticlegivesareviewonexpressionbodiedmemberswithC#6,andshowsthenewoptionswithC#7.0. Expression-BodiedMethods(C#6) Withexpression-bodiedmethods,amethodthatincludesjustonestatementcanbewrittenwiththelambdasyntax: C#5.0 publicboolIsSquare(Rectanglerect) { returnrect.Height==rect.Width; } C#6 publicboolIsSquare(Rectanglerect)=>rect.Height==rect.Width; Thisremovesnotonlythecurlybrackets,butalsothereturnkeyword.Returnisimplicitwithalambdaexpression. Lambdaexpressionscanbewritteninshortformwithoutcurlybracketswhenthestatementconsistsofasingleline.Lambdaexpressionscanalsobewritteninthelongformwherecurlybracketsandthereturnstatementareneeded.Thislongersyntaxisnotpossiblewithexpression-bodiedmembers.Ifonecodelineisnotenough,youcanusethenormalsyntaxwithcurlybrackets,asisavailablesinceC#1.0. Expression-BodiedProperties(C#6) Similartoexpression-bodiedmethods,one-linepropertieswithonlyagetaccessorcanbewrittenwiththesamelambdasyntax. C#5.0 publicstringFullName { get { returnFirstName+""+LastName; } } C#6 publicstringFullName=>FirstName+""+LastName; Thissyntaxreducesthecodenotonlybyremovingcurlybrackets,butalsowritingthegetaccessorisnotnecessary.Thecodethat’sgeneratedfromthecompileristhesame. Expression-BodiedConstructors(C#7.0) Afterwe’reusedtotheshortersyntax,expression-bodiedmemberscannowbewrittenwithconstructorsaswell.Incasetheconstructorjustneedsoneline,thecodecanbesimplified: C#6 publicResource() { Console.WriteLine($"ctor{nameof(Resource}"); } C#7.0 publicResource()=>Console.WriteLine($"ctor{nameof(Resource}"); Expression-BodiedDestructors(C#7.0) Thesameistruefordestructors: C#6 public~Resource() { Console.WriteLine($"destructor{nameof(Resource}"); } C#7.0 public~Resource()=>Console.WriteLine($"destructor{nameof(Resource}"); Expression-BodiedPropertyAccessors(C#7.0) Withthenewoptionsforexpression-bodiedmembers,Iseethebiggestadvantageinexpression-bodiedpropertyaccessors.Withaccessorsthatconsistofjustoneline,thecodecanbesimplified: C#6 privateint_x; publicX { get { return_x; } set { _x=value; } } C#7.0 privateint_x; publicX { get=>_x; set=>_x=value; } Ofcourseinsuchasimplescenario,Iwoulduseanautoproperty(availablesinceC#2.0),whichreducesthecodemore: publicintX{get;set;} However,Ioftenneedpropertieswithadifferentimplementation,e.g.usingaINotifyPropertyChangedimplementationfromabaseclass.Here,getandsetaccessorsareneeded: C#6 privateint_x; publicX { get { return_x; } set { SetProperty(ref_x,value); } } Thisisnowausefulexampleoftheshorthandnotation: C#7.0 privateint_x; publicX { get=>_x; set=>SetProperty(ref_x,value); } Expression-BodiedEventAccessors Ofcourseexpression-bodiesalsoworkwithevents.Insteadofwriting C#6 privateEventHandler_someEvent; publiceventEventHandlerSomeEvent { add { _someEvent+=value; } remove { _someEvent-=value; } } Youcannowwrite: C#7.0 privateEventHandler_someEvent; publiceventEventHandlerSomeEvent { add=>_someEvent+=value; remove=>_someEvent-=value; } Ofcourseinsuchasimplescenarioyoucanalsousetheshorthandnotationasfollows.However,inscenarioswhereyouneedtodomore(describedinmybookProfessioinalC#6),thenewsyntaxcanbehelpful. C# publiceventEventHandlerSomeEvent; Summary C#7.0continueswithproductivityenhancements.Expression-bodiedmembershavebeenavailablewithC#6formethodsandproperties,nowtheycanbeusedwithconstructors,destructors,propertyaccessors,andeventaccessorsaswell. Related OtherC#7.0featuresI’vealreadywrittenabout: BinaryLiteralsandDigitSeparators Tuples SampleCode ThesamplecodeisavailableatGitHub. TorunthesamplecodeyouneedVisualStudio2017RC. Havefunwithprogrammingandlearning! Christian MoreInformation Update:moreinformationonC#7featuresinmynewbookProfessionalC#7and.NETCore2.0withsourcecodeupdatesatGitHub. MoreinformationaboutC#andexpression-bodiedmembersisavailableinmynewbookandmyC#workshops: ProfessionalC#6and.NETCore1.0 ChristianNagel’sWorkshops Imagefrom©Massimocampanari|Dreamstime.comLANCIALambdaSpiderCorsaMM1928 Sharethis:TwitterFacebookLikethis:LikeLoading... Publishedby ChristianNagel MicrosoftMVPforDeveloperTechnologies,softwarearchitect,developer,bookauthor,trainerandconsultant ViewallpostsbyChristianNagel 7thoughtson“C#7.0ExpressionBodiedMembers” Nicejob.Whatplugindoyouusetopostcodeonyourblog? LikeLike Reply I’musingaGitrepositorytomanageexistingandupcomingblogposts,useVisualStudioCodetowriteMarkdowntext,anddirectly uploadit totheWordPressWebsite. LikeLike Reply Pingback:Szumma#077–20175.hét|d/fuel Pingback:Lesliensdelasemaine–Édition#219|FrenchCoding Pingback:C#7.0–PatternMatching–csharp.christiannagel.com Pingback:C#7.0–What’sNew–csharp.christiannagel.com Pingback:LocalFunctions–What’stheValue?–csharp.christiannagel.com LeaveaReplyCancelreply Enteryourcommenthere... Fillinyourdetailsbeloworclickanicontologin: Email(required)(Addressnevermadepublic) Name(required) Website YouarecommentingusingyourWordPress.comaccount. ( Log Out /  Change ) YouarecommentingusingyourGoogleaccount. ( Log Out /  Change ) YouarecommentingusingyourTwitteraccount. ( Log Out /  Change ) YouarecommentingusingyourFacebookaccount. ( Log Out /  Change ) Cancel Connectingto%s Notifymeofnewcommentsviaemail.Notifymeofnewpostsviaemail. Δ ThissiteusesAkismettoreducespam.Learnhowyourcommentdataisprocessed. Postnavigation PreviousPreviouspost:OpenTabItemsDynamicallywithUWPNextNextpost:C#7.0OutVarsandRefReturns Follow Following csharp.christiannagel.com Join2,287otherfollowers Signmeup AlreadyhaveaWordPress.comaccount?Loginnow. csharp.christiannagel.com Customize Follow Following Signup Login Copyshortlink Reportthiscontent ViewpostinReader Managesubscriptions Collapsethisbar Privacy&Cookies:Thissiteusescookies.Bycontinuingtousethiswebsite,youagreetotheiruse. Tofindoutmore,includinghowtocontrolcookies,seehere: OurCookiePolicy %dbloggerslikethis:



請為這篇文章評分?