C# Partial Classes and Methods - TutorialsTeacher

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

In C#, you can split the implementation of a class, a struct, a method, or an interface in multiple .cs files using the partial keyword. C# ASP.NETCore MVC IoC TypeScript Angular Python SQLServer MongoDB More ✕ .NETTutorials C# ASP.NETCore ASP.NETMVC IoC WebAPI LINQ ClientSide JavaScript jQuery Node.js D3.js TypeScript Angular11 AngularJS1 Sass ServerSide Golang Python https SQL SQLServer PostgreSQL MongoDB SkillTests ASP.NETCore ASP.NETMVC LINQ C# webapi IoC TypeScript AngularJS Node.js jQuery JavaScript Articles Tests LearnC# C#-GetStarted C#-VersionHistory C#-FirstProgram C#-Keywords C#-Class C#-Namespace C#-Variable C#-Implicitly-TypedVariable C#-DataTypes Numbers Strings DateTime Structure Enum StringBuilder AnonymousTypes DynamicTypes NullableTypes C#-Value&ReferenceTypes C#-Interface C#-Operators C#-ifelseStatements C#-TernaryOperator?: C#-Switch C#-ForLoop C#-WhileLoop C#-Do-whileLoop C#-PartialClass C#-Static C#-Array MultidimensionalArray JaggedArray C#-Indexer C#-Generics GenericConstraints C#-Collections ArrayList List SortedList Dictionary Hashtable Stack Queue C#-Tuple C#-ValueTuple C#-Built-inExceptions ExceptionHandling throw CustomException C#-Delegates FuncDelegate ActionDelegate PredicateDelegate AnonymousMethods C#-Events C#-Covariance C#-ExtensionMethod C#-StreamI/O C#-File C#-FileInfo C#-ObjectInitializer C#-UsefulResources Previous Next C#-PartialClassesandMethods InC#,youcansplittheimplementationofaclass,astruct,amethod,oraninterfaceinmultiple.csfilesusingthepartialkeyword. Thecompilerwillcombinealltheimplementationfrommultiple.csfileswhentheprogramiscompiled. ConsiderthefollowingEmployeeProps.csandEmployeeMethods.csfilesthatcontaintheEmployeeclass. EmployeeProps.cs publicpartialclassEmployee { publicintEmpId{get;set;} publicstringName{get;set;} } EmployeeMethods.cs publicpartialclassEmployee { //constructor publicEmployee(intid,stringname){ this.EmpId=id; this.Name=name; } publicvoidDisplayEmpInfo(){ Console.WriteLine(this.EmpId+""this.Name); } } Above,EmployeeProps.cscontainspropertiesoftheEmployeeclass,andEmployeeMethods.cscontainsallthemethodsoftheEmployeeclass.ThesewillbecompiledasoneEmployeeclass. Example:CombinedClass publicclassEmployee { publicintEmpId{get;set;} publicstringName{get;set;} publicEmployee(intid,stringname){ this.EmpId=id; this.Name=name; } publicvoidDisplayEmpInfo(){ Console.WriteLine(this.EmpId+""this.Name); } } RulesforPartialClasses Allthepartialclassdefinitionsmustbeinthesameassemblyandnamespace. Allthepartsmusthavethesameaccessibilitylikepublicorprivate,etc. Ifanypartisdeclaredabstract,sealedorbasetypethenthewholeclassisdeclaredofthesametype. Differentpartscanhavedifferentbasetypesandsothefinalclasswillinheritallthebasetypes. ThePartial modifiercanonlyappearimmediatelybeforethekeywords class, struct,or interface. Nestedpartialtypesareallowed. PartialMethods Partialclassesorstructscancontainamethodthatsplitintotwoseparate.csfilesofthepartialclassorstruct. Oneofthetwo.csfilesmustcontainasignatureofthemethod,andotherfilecancontainanoptionalimplementationofthepartialmethod. Bothdeclarationandimplementationofamethodmusthavethepartialkeyword. EmployeeProps.cs publicpartialclassEmployee { publicEmployee(){ GenerateEmpId(); } publicintEmpId{get;set;} publicstringName{get;set;} partialvoidGenerateEmployeeId(); } EmployeeMethods.cs publicpartialclassEmployee { partialvoidGenerateEmployeeId() { this.EmpId=random(); } } Above,EmployeeProps.cscontainsthedeclarationofthepartialmethodGenerateEmployeeId()whichisbeingusedintheconstructor. EmployeeMethods.cscontainstheimplementationoftheGenerateEmployeeId()method. ThefollowingdemonstratescreatesanobjecttheEmployeeclasswhichusedthepartialmethod. EmployeeMethods.cs classProgram { staticvoidMain(string[]args) { varemp=newEmployee(); Console.WriteLine(emp.EmpId);//printsgeneretedid Console.ReadLine(); } } RulesforPartialMethods Partialmethodsmustusethepartialkeywordandmustreturnvoid. Partialmethodscanhaveinorrefbutnotoutparameters. Partialmethodsareimplicitlyprivatemethods,socannotbevirtual. Partialmethodscanbestaticmethods. Partialmethodscanbegeneric. Learnmoreaboutpartialclassesandmethoshere. C#Questions&Answers StartC#SkillTest RelatedArticles DifferencebetweenArrayandArrayList DifferencebetweenHashtableandDictionary HowtowritefileusingStreamWriterinC#? HowtosortthegenericSortedListinthedescendingorder? DifferencebetweendelegatesandeventsinC# HowtoreadfileusingStreamReaderinC#? HowtocalculatethecodeexecutiontimeinC#? DesignPrinciplevsDesignPattern HowtoconvertstringtointinC#? BoxingandUnboxinginC# MoreC#articles Previous Next Share Tweet Share Whatsapp C#Questions&Answers C#SkillTest C#LatestArticles



請為這篇文章評分?