Partial Classes and Methods - C# Programming Guide
文章推薦指數: 80 %
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
延伸文章資訊
- 1Partial Classes in C# - GeeksforGeeks
A partial class is a special feature of C#. It provides a special ability to implement the functi...
- 2C# Partial Class and Partial Method (With Examples)
A partial class may contain a partial method. One part of the class contains the signature of the...
- 3C# Partial Classes and Methods - TutorialsTeacher
In C#, you can split the implementation of a class, a struct, a method, or an interface in multip...
- 4部分類別和方法- C# 程式設計手冊 - Microsoft Learn
partial 修飾詞只能緊貼在關鍵字 class 、 struct 或 interface 之前。 部分型別定義中允許巢狀部分型別,如下例所示︰. C# 複製.
- 5Learn all about Partial Class in C# | Simplilearn