C# Partial Classes and Methods - TutorialsTeacher
文章推薦指數: 80 %
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
延伸文章資訊
- 1[.NET C#] Partial Classes 部份類別| KC Lin - - 點部落
C# 2.0 開始支援了部份類別(Partial Class) 的機制,即便在同一個Class底下也可以分別寫在不同的source code file裡,而在.
- 2Partial Classes in C# - GeeksforGeeks
A partial class is a special feature of C#. It provides a special ability to implement the functi...
- 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...
- 4Partial Classes and Methods - C# Programming Guide
Partial classes and methods in C# split the definition of a class, a struct, an interface, or a m...
- 5C# - 使用Partial Classes | 張小呆的碎碎唸 - - 點部落
摘要:C# - 使用Partial Classes. 從以前到現在都沒用過Partial Classes,因為專案的關係,終於有機會使用了。一般來說,當我們定義好介面( Interface ) ...