Learn all about Partial Class in C# | Simplilearn
文章推薦指數: 80 %
Partial Class is a unique feature of C#. It can break the functionality of a single class into many files. When the application is compiled, ...
SoftwareDevelopmentDataScience&BusinessAnalyticsAI&MachineLearningProjectManagementCyberSecurityCloudComputingDevOpsBusinessandLeadershipQualityManagementSoftwareDevelopmentAgileandScrumITServiceandArchitectureDigitalMarketingBigDataCareerFast-trackEnterpriseOtherSegmentsArticlesEbooksFreePracticeTestsOn-demandWebinarsVideoTutorialsHomeResourcesSoftwareDevelopmentLearnallaboutPartialClassinC#TrendingnowTopGoldmanSachsInterviewQuestionsandAnswersfor2022ArticleEverythingYouNeedtoKnowAbouttheDesignPatternsinJavaArticleBlockchainCareerGuide:AComprehensivePlaybookToBecomingABlockchainDeveloperEbookEverythingYouNeedtoKnowAboutIteratorsinC++ArticleTryingYourHandsonJava?Here’saGuidetoHelpYouAddaNewLineinJavaScriptArticleTheBestGuidetoKnowWhatIsVueJSVideoTutorialBestProgrammingLanguagestoLearnin2022ArticleListtoStringinPythonArticleCProgramforBubbleSorttoSortElementsinanOrderArticleAngularJSVs.Angular2Vs.Angular4:UnderstandingtheDifferencesArticleLearnallaboutPartialClassinC#BySimplilearnLastupdatedonFeb22,20224237TableofContentsViewMore
Eachsourcefilecontainsthedefinitionanddeclarationofmethodsthatarecombinedwhenanapplicationiscompiled.Wecansplitclasses,structures,interfaces,andothermethodsusingthevarioussourcefiles.
Partialclasseshelpsplitthemethodsintotwoormoresource(.cs)files.Allthepartialclasseswillbecombinedwhenthewholeprogramiscompiled.
PartialClassisauniquefeatureofC#.Itcanbreakthefunctionalityofasingleclassintomanyfiles.Whentheapplicationiscompiled,thesefilesarethenreassembledintoasingleclassfile.Thepartialkeywordisusedtobuildapartialclass.
PostGraduateProgram:FullStackWebDevelopmentinCollaborationwithCaltechCTMEEnrollNow
UseofPartialClasses
Followingarethescenarioswheresplittingthefilesbecomesnecessary:
Ifyouareworkingonabiggerproject,splittingthefilesoverdifferentclasseshelpsdevelopersworkonthesameprojectsimultaneously.
Ifyouareworkingonanautomaticallygeneratedsource,thenthecodecanbeaddedtotheclasswithoutregeneratingthesourcefile.
Thevisualstudiowhichcreateswindowsforms,webservicewrappercode,andsomeotherfilesautomatically,usesthispartialclassmethodtosplititintofileswithoutmodifyingthem.
Partialclassescanbehelpfulifyouareusingsourcegeneratorstogenerateadditionalfunctionality.
Wecansplittheclassdefinitionbyusingthepartialkeywordmodifierasshownintheimagebelow.
Thepartialkeyworddenotesthatotherpartsofclass,method,andfunctioncanbedefinedhere.
publicpartialclassStudents{
privatestringName;
privateintRollno;
publicStudents(stringa,intt)
{
this.Student_name=a;
this.Roll_no=t;
}
}
Listedbelowaresomeofthefiletypeswhicharemergedfromthepartialclasses:
XMLcomments
interfaces
generic-typeparameterattributes
classattributes
members
NewCourse:FullStackDevelopmentforBeginnersLearnGitCommand,Angular,NodeJS,Maven&MoreEnrollNow
AdvantagesofaPartialClass
1.Withthehelpofpartialclasses,youcanseparateUIdesigncodeandbusinesslogiccode.
Forinstance,ifwedevelopawebapplicationusingthevisualstudio,someofthesourcefileswillgetadded.Thesefileswillhavepartialkeywords.Thereisa".aspx.cs"classthathasthebusinesslogiccodeand"aspx.designer.cs"thathasuserinterfacecontroldefinition.
2.Wearenotrequiredtoregeneratethesourcefilewhenworkingwithautomatically-generatedfiles.
Forinstance,whenworkingwithLINQtoSQLandcreatingaDBMLfile.Whenwecopyandpasteatable,itwillcreateapartialclassindesigner.cs.Sotonotaddnewcolumns,wecancreateaseparatesourcefilefortheclass,whichwillactasapartialclass.
3.Moredeveloperscanworksimultaneouslyonthesameproject.
4.Itiseasiertomaintain,understand,anddevelopapartialclassthanahugeclassforthewholeprogram.Ahugefilecanbeconvertedintomanypartialclassescontainingvariousmethodsandclasses.
PointstoRemember
Allpartialclassesmustcontainthepartialkeyword.
Partialclassescanelaborateonvariousbaseclassesthatwillbecombinedatthecompilertime.Anymethod,interface,andfunctiondeclaredonapartialclassisavailableforalltheotherparts.
Thesourcefilenameforeachpartofthepartialclasscanbedifferent,buteachpartialclass’snamemustbethesame.
Thenameofallpartsofapartialclassshouldbethesame.
Allpartsofapartialclassshouldbeinthesameassembly.
Allclassesshouldhavepublic,private,oranotheraccessibilitymodifier;theaccessibilityofeachpartofthepartialclassshouldbethesame.
Ifweinheritaclassormethodonapartialclass,itwillalsobeinheritedforallpartsofthepartialclass.
Ifanypartoftheclassisdeclaredwithanyspecificaccessmodifier,thenthewholeclasswillbeconsideredofthesametype.
Ifanypartoftheclassisdeclaredabstract,thenthewholetypeisabstract,andifanyclassisdeclaredsealed,thewholeclassissealed.
Example:
Wewillcreateapartialclassthatwillhelpusunderstandtheuseofpartialclassesinourprojects.
Inthisexample,weareworkingwithLINQtoSQLapplicationstocreateName,Rollno,andDateofBirthcolumnsforstudents.WewillthencreateaseparatepartialclasswithaRollnoproperty.
1.Createa"Student"tableinthedatabase.
Wewillneedtocreateastudenttableinthedatabasethathasthethreefields"Name","RollNo",and"DateOfBirth".The"Name"fieldistheprimarykey.
CREATETABLEStudent
(
Classintidentity(1,1)primarykey,
Namenvarchar(50),
DateOfBirthDatedefaultgetUtcDate()
)
2.Wewillcreateawebapplicationfromthevisualstudio.
3.Next,wewilladdanewclassusingtheaddfunctiononthesolutionexplorer.
4.Choose"LINQtoSQLClasses"fromthelistofpartialclassesandprovidethename"Student"fortheDBMLname.Thenwewillclickon"Add".
5.WewillthencopytheUsertablefromthedatabaseintheServerExplorerandpasteitintotheDesignersurfaceofthe"Student.dbml"file.
6.Nowwecanopenthe"Student.designer.cs"file.Weseethe"Student"partialclasshasbeencreated.Wecannowdraganddropa"Student"tablefromthedatabaseonthesurface.
7.CreateaUIdesigntoshowstudents’detailsinthegridviewfromthedataprovided.
FullStackWebDeveloperCourseTobecomeanexpertinMEANStackViewCourse
8.Wewillwritecodeforthe"Page_Load"eventtobindagridviewbystudentlistinthecodebehindthefile.
usingSystem;
usingSystem.Linq;
namespacePartialClassExample
{
publicpartialclassStudentUI:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
using(StudentDataContextcontext=newStudentDataContext())
{
varquery=fromstudentincontext.GetTable
延伸文章資訊
- 1C# - 使用Partial Classes | 張小呆的碎碎唸 - - 點部落
從以前到現在都沒用過Partial Classes,因為專案的關係,終於有機會使用了。一般來說,當我們定義好介面( Interface )後,就要開始實作介面的功能。
- 2c# partial class 的用法_kankankankan2222的博客
partial class A 就是说明这是类A 只是一部分。我可以在创建一个类B.cs。在代码里也写partial class A。那么程序在编译后。两个A中的属性和方法会合并 ...
- 3[.NET C#] Partial Classes 部份類別| KC Lin - - 點部落
C# 2.0 開始支援了部份類別(Partial Class) 的機制,即便在同一個Class底下也可以分別寫在不同的source code file裡,而在.
- 4Partial Classes and Methods - C# Programming Guide
A partial class or struct may contain a partial method. One part of the class contains the signat...
- 5cs檔分身術:partial class - iT 邦幫忙::一起幫忙解決難題
而當加上該關鍵字以後的class name就可以分別存於不同cs檔,如下: //filename : test.cs namespace IThome { public partial clas...