Partial Classes and Methods - C# Programming Guide

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

Partial classes and methods in C# split the definition of a class, a struct, an interface, or a method over two or more source files. Skiptomaincontent Thisbrowserisnolongersupported. UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport. DownloadMicrosoftEdge MoreinfoaboutInternetExplorerandMicrosoftEdge Tableofcontents Exitfocusmode ReadinEnglish Save Tableofcontents ReadinEnglish Save Feedback Edit Twitter LinkedIn Facebook Email Tableofcontents PartialClassesandMethods(C#ProgrammingGuide) Article 01/25/2022 6minutestoread 20contributors Inthisarticle Itispossibletosplitthedefinitionofaclass,astruct,aninterfaceoramethodovertwoormoresourcefiles.Eachsourcefilecontainsasectionofthetypeormethoddefinition,andallpartsarecombinedwhentheapplicationiscompiled. PartialClasses Thereareseveralsituationswhensplittingaclassdefinitionisdesirable: Whenworkingonlargeprojects,spreadingaclassoverseparatefilesenablesmultipleprogrammerstoworkonitatthesametime. Whenworkingwithautomaticallygeneratedsource,codecanbeaddedtotheclasswithouthavingtorecreatethesourcefile.VisualStudiousesthisapproachwhenitcreatesWindowsForms,Webservicewrappercode,andsoon.YoucancreatecodethatusestheseclasseswithouthavingtomodifythefilecreatedbyVisualStudio. Whenusingsourcegeneratorstogenerateadditionalfunctionalityinaclass. Tosplitaclassdefinition,usethepartialkeywordmodifier,asshownhere: publicpartialclassEmployee { publicvoidDoWork() { } } publicpartialclassEmployee { publicvoidGoToLunch() { } } Thepartialkeywordindicatesthatotherpartsoftheclass,struct,orinterfacecanbedefinedinthenamespace.Allthepartsmustusethepartialkeyword.Allthepartsmustbeavailableatcompiletimetoformthefinaltype.Allthepartsmusthavethesameaccessibility,suchaspublic,private,andsoon. Ifanypartisdeclaredabstract,thenthewholetypeisconsideredabstract.Ifanypartisdeclaredsealed,thenthewholetypeisconsideredsealed.Ifanypartdeclaresabasetype,thenthewholetypeinheritsthatclass. Allthepartsthatspecifyabaseclassmustagree,butpartsthatomitabaseclassstillinheritthebasetype.Partscanspecifydifferentbaseinterfaces,andthefinaltypeimplementsalltheinterfaceslistedbyallthepartialdeclarations.Anyclass,struct,orinterfacemembersdeclaredinapartialdefinitionareavailabletoalltheotherparts.Thefinaltypeisthecombinationofallthepartsatcompiletime. Note Thepartialmodifierisnotavailableondelegateorenumerationdeclarations. Thefollowingexampleshowsthatnestedtypescanbepartial,evenifthetypetheyarenestedwithinisnotpartialitself. classContainer { partialclassNested { voidTest(){} } partialclassNested { voidTest2(){} } } Atcompiletime,attributesofpartial-typedefinitionsaremerged.Forexample,considerthefollowingdeclarations: [SerializableAttribute] partialclassMoon{} [ObsoleteAttribute] partialclassMoon{} Theyareequivalenttothefollowingdeclarations: [SerializableAttribute] [ObsoleteAttribute] classMoon{} Thefollowingaremergedfromallthepartial-typedefinitions: XMLcomments interfaces generic-typeparameterattributes classattributes members Forexample,considerthefollowingdeclarations: partialclassEarth:Planet,IRotate{} partialclassEarth:IRevolve{} Theyareequivalenttothefollowingdeclarations: classEarth:Planet,IRotate,IRevolve{} Restrictions Thereareseveralrulestofollowwhenyouareworkingwithpartialclassdefinitions: Allpartial-typedefinitionsmeanttobepartsofthesametypemustbemodifiedwithpartial.Forexample,thefollowingclassdeclarationsgenerateanerror:publicpartialclassA{} //publicclassA{}//Error,mustalsobemarkedpartial Thepartialmodifiercanonlyappearimmediatelybeforethekeywordsclass,struct,orinterface. Nestedpartialtypesareallowedinpartial-typedefinitionsasillustratedinthefollowingexample:partialclassClassWithNestedClass { partialclassNestedClass{} } partialclassClassWithNestedClass { partialclassNestedClass{} } Allpartial-typedefinitionsmeanttobepartsofthesametypemustbedefinedinthesameassemblyandthesamemodule(.exeor.dllfile).Partialdefinitionscannotspanmultiplemodules. Theclassnameandgeneric-typeparametersmustmatchonallpartial-typedefinitions.Generictypescanbepartial.Eachpartialdeclarationmustusethesameparameternamesinthesameorder. Thefollowingkeywordsonapartial-typedefinitionareoptional,butifpresentononepartial-typedefinition,cannotconflictwiththekeywordsspecifiedonanotherpartialdefinitionforthesametype: public private protected internal abstract sealed baseclass newmodifier(nestedparts) genericconstraints Formoreinformation,seeConstraintsonTypeParameters. Examples Inthefollowingexample,thefieldsandtheconstructoroftheclass,Coords,aredeclaredinonepartialclassdefinition,andthemember,PrintCoords,isdeclaredinanotherpartialclassdefinition. publicpartialclassCoords { privateintx; privateinty; publicCoords(intx,inty) { this.x=x; this.y=y; } } publicpartialclassCoords { publicvoidPrintCoords() { Console.WriteLine("Coords:{0},{1}",x,y); } } classTestCoords { staticvoidMain() { CoordsmyCoords=newCoords(10,15); myCoords.PrintCoords(); //Keeptheconsolewindowopenindebugmode. Console.WriteLine("Pressanykeytoexit."); Console.ReadKey(); } } //Output:Coords:10,15 Thefollowingexampleshowsthatyoucanalsodeveloppartialstructsandinterfaces. partialinterfaceITest { voidInterface_Test(); } partialinterfaceITest { voidInterface_Test2(); } partialstructS1 { voidStruct_Test(){} } partialstructS1 { voidStruct_Test2(){} } PartialMethods Apartialclassorstructmaycontainapartialmethod.Onepartoftheclasscontainsthesignatureofthemethod.Animplementationcanbedefinedinthesamepartoranotherpart.Iftheimplementationisnotsupplied,thenthemethodandallcallstothemethodareremovedatcompiletime.Implementationmayberequireddependingonmethodsignature.Apartialmethodisn'trequiredtohaveanimplementationinthefollowingcases: Itdoesn'thaveanyaccessibilitymodifiers(includingthedefaultprivate). Itreturnsvoid. Itdoesn'thaveanyoutparameters. Itdoesn'thaveanyofthefollowingmodifiersvirtual,override,sealed,new,orextern. Anymethodthatdoesn'tconformtoallthoserestrictions(forexample,publicvirtualpartialvoidmethod),mustprovideanimplementation.Thatimplementationmaybesuppliedbyasourcegenerator. Partialmethodsenabletheimplementerofonepartofaclasstodeclareamethod.Theimplementerofanotherpartoftheclasscandefinethatmethod.Therearetwoscenarioswherethisisuseful:templatesthatgenerateboilerplatecode,andsourcegenerators. Templatecode:Thetemplatereservesamethodnameandsignaturesothatgeneratedcodecancallthemethod.Thesemethodsfollowtherestrictionsthatenableadevelopertodecidewhethertoimplementthemethod.Ifthemethodisnotimplemented,thenthecompilerremovesthemethodsignatureandallcallstothemethod.Thecallstothemethod,includinganyresultsthatwouldoccurfromevaluationofargumentsinthecalls,havenoeffectatruntime.Therefore,anycodeinthepartialclasscanfreelyuseapartialmethod,eveniftheimplementationisnotsupplied.Nocompile-timeorrun-timeerrorswillresultifthemethodiscalledbutnotimplemented. Sourcegenerators:Sourcegeneratorsprovideanimplementationformethods.Thehumandevelopercanaddthemethoddeclaration(oftenwithattributesreadbythesourcegenerator).Thedevelopercanwritecodethatcallsthesemethods.Thesourcegeneratorrunsduringcompilationandprovidestheimplementation.Inthisscenario,therestrictionsforpartialmethodsthatmaynotbeimplementedoftenaren'tfollowed. //Definitioninfile1.cs partialvoidOnNameChanged(); //Implementationinfile2.cs partialvoidOnNameChanged() { //methodbody } Partialmethoddeclarationsmustbeginwiththecontextualkeywordpartial. Partialmethodsignaturesinbothpartsofthepartialtypemustmatch. Partialmethodscanhavestaticandunsafemodifiers. Partialmethodscanbegeneric.Constraintsareputonthedefiningpartialmethoddeclaration,andmayoptionallyberepeatedontheimplementingone.Parameterandtypeparameternamesdonothavetobethesameintheimplementingdeclarationasinthedefiningone. Youcanmakeadelegatetoapartialmethodthathasbeendefinedandimplemented,butnottoapartialmethodthathasonlybeendefined. C#LanguageSpecification Formoreinformation,seePartialtypesintheC#LanguageSpecification.ThelanguagespecificationisthedefinitivesourceforC#syntaxandusage. Seealso C#ProgrammingGuide Classes Structuretypes Interfaces partial(Type) Feedback Submitandviewfeedbackfor Thisproduct Thispage Viewallpagefeedback Inthisarticle



請為這篇文章評分?