C# Partial Class and Partial Method (With Examples)

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

A partial class may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials C#"HelloWorld"Program OperatorsinC# C#ifStatement C#foreachLoop C#forLoop StartLearningC# LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials C#"HelloWorld"Program OperatorsinC# C#ifStatement C#foreachLoop C#forLoop StartLearningC# AllC#Tutorials Python JavaScript C C++ Java Kotlin PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples Introduction C#HelloWorld C#Keywords&Identifiers C#Variables C#Operators C#OperatorPrecedence C#BitwiseOperators C#BasicI/O C#Expressions&Statements C#Comments FlowControl C#if...else C#switchStatement C#TernaryOperator C#forLoop C#whileLoop C#NestedLoops C#breakStatement C#continueStatement Arrays C#Arrays C#MultidimensionalArrays C#JaggedArray C#foreachLoop OOP(I) C#ClassandObjects C#Methods C#AccessModifiers C#VariableScope C#Constructors C#thisKeyword C#staticKeyword C#Strings OOP(II) C#Inheritance C#AbstractClass&Methods C#NestedClass C#PartialClass C#SealedClass C#Interface C#MethodOverloading C#ConstructorOverloading AdditionalTopics C#using C#TypeConversion C#PreprocessorDirectives C#Namespaces C#struct RelatedTopics C#KeywordsandIdentifiers C#abstractclassandmethod C#sealedclassandmethod C#ClassandObject C#Method C#NestedClass C#PartialClassandPartialMethod InthisarticlewearegoingtolearnabouthowandwhypartialclassandpartialmethodsbeimplementedinC#. Therearemanysituationswhenyoumightneedtosplitaclassdefinition, suchaswhenworkingonalargescaleprojects,multipledevelopersandprogrammersmightneedtoworkonthesameclassatthesametime.InthiscasewecanuseafeaturecalledPartialClass. IntroductiontoPartialClass WhileprogramminginC#(orOOP),wecansplitthedefinitionofaclassovertwoormoresourcefiles.Thesourcefilescontainsasectionofthedefinitionofclass,andallpartsarecombinedwhentheapplicationiscompiled.Forsplittingaclassdefinition,weneedtousethepartialkeyword. Example1: WehaveaprojectnamedasHeightWeightInfowhichshowsheightandweight. WehaveafilenamedasFile1.cswithapartialclassnamedasRecord.Ithastwointegervariablesh&wandamethod/constructornamedasRecordwhichisassigningthevaluesofh&w. namespaceHeightWeightInfo { classFile1 { } publicpartialclassRecord { privateinth; privateintw; publicRecord(inth,intw) { this.h=h; this.w=w; } } } HereisanotherfilenamedasFile2.cswiththesamepartialclassRecordwhichhasonlythemethodPrintRecord.Thismethodwilldisplaythevaluesofh&w. namespaceHeightWeightInfo { classFile2 { } publicpartialclassRecord { publicvoidPrintRecord() { Console.WriteLine("Height:"+h); Console.WriteLine("Weight:"+w); } } } Herenowwecanseethemainmethodoftheproject: namespaceHeightWeightInfo { classProgram { staticvoidMain(string[]args) { RecordmyRecord=newRecord(10,15); myRecord.PrintRecord(); Console.ReadLine(); } } } HerewehavetheobjectoftheclassRecordasmyRecordwhichispassingtheparametervaluesas10and15tohandwrespectivelytothemethoddefinedinFile1.cs. ThemethodPrintRecordiscalledbytheobjectmyRecordwhichisdefinedintheFile2.cs. Thisshowsthatthepartialkeywordhelpstocombinealltheattributesofaclassdefinedinvariousfilestoworkasasingleclass. Placeswherepartialclasscanbeused: Whileworkingonalargerprojectswithmorethanonedeveloper,ithelpsthedeveloperstoworkonthesameclasssimultaneously. Codescanbeaddedormodifiedtotheclasswithoutre-creatingsourcefileswhichareautomaticallygeneratedbytheIDE(i.e.VisualStudio). ThingstoRememberaboutPartialClass Thepartialkeywordspecifythatotherpartsoftheclasscanbedefinedinthenamespace.Itismandatorytousethepartialkeywordifwearetryingtomakeaclasspartial.Allthepartsoftheclassshouldbeinthesamenamespaceandavailableatcompiletimetoformthefinaltype.Allthepartsmusthavesameaccessmodifieri.e.private,public,orsoon. Ifanypartisdeclaredabstract,thenthewholetypeisconsideredabstract. Ifanypartisdeclaredsealed,thenthewholetypeisconsideredsealed. Ifanypartdeclaresabasetype,thenthewholetypeinheritsthatclass. Anyclassmemberdeclaredinapartialdefinitionareavailabletoallotherparts. Allpartsofapartialclassshouldbeinthesamenamespace. **Note:Thepartialmodifierisnotavailableondelegateorenumerationdeclarations IntroductiontoPartialMethods Apartialclassmaycontainapartialmethod.Onepartoftheclasscontainsthesignatureofthemethod.Anoptionalimplementationmaybedefinedinthesamepartoranotherpart.Iftheimplementationisnotsupplied,thenthemethodandallcallsareremovedatcompiletime. Example2: Let'stakeanexampleasapartialclassCardefinedinfile1.cswhichhasthreemethodsInitializeCar(),BuildRim()andBuildWheels().Amongthosemethods,InitializeCarisdefinedaspartial. publicpartialclassCar { partialvoidInitializeCar(); publicvoidBuildRim(){} publicvoidBuildWheels(){} } Andwehaveanotherfilenamedasfile2.cswhichhastwomethodsBuildEngineandInitializeCar.ThemethodInitializeCarispartialmethodwhichisalsodefinedinfile1.cs. publicpartialclassCar { publicvoidBuildEngine(){} partialvoidInitializeCar() { stringstr="Car"; } } Apartialmethoddeclarationconsistsoftwoparts: Thedefinitionasinfile1.cs. Theimplementationasinfile2.cs. Theymaybeinseparatepartsofthepartialclass,orinthesamepart. ThingstorememberaboutPartialMethod partialkeyword. returntypevoid. implicitlyprivate. andcannotbevirtual. TableofContents IntroductiontoPartialClass Example ThingstoRemember IntroductiontoPartialMethods Example ThingstoRemember PreviousTutorial: C#NestedClass NextTutorial: C#SealedClass Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsC#TutorialC#KeywordsandIdentifiersC#TutorialC#abstractclassandmethodC#TutorialC#sealedclassandmethodC#TutorialC#Method



請為這篇文章評分?