C# Partial Class and Partial Method (With Examples)
文章推薦指數: 80 %
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
延伸文章資訊
- 1[.NET C#] Partial Classes 部份類別| KC Lin - - 點部落
C# 2.0 開始支援了部份類別(Partial Class) 的機制,即便在同一個Class底下也可以分別寫在不同的source code file裡,而在.
- 2C# Partial Classes and Methods - TutorialsTeacher
In C#, you can split the implementation of a class, a struct, a method, or an interface in multip...
- 3Partial Classes in C# - GeeksforGeeks
A partial class is a special feature of C#. It provides a special ability to implement the functi...
- 4部分類別和方法- C# 程式設計手冊 - Microsoft Learn
partial 修飾詞只能緊貼在關鍵字 class 、 struct 或 interface 之前。 部分型別定義中允許巢狀部分型別,如下例所示︰. C# 複製.
- 5cs檔分身術:partial class - iT 邦幫忙::一起幫忙解決難題
即使將公共的lib拆出去,也無法避免公共層過大。經學長推薦,筆者研讀lidgren原始碼,才了解C# 有一個特殊的用法partial可以協助Prgrammer採分檔案。