Partial (type) (C # Reference)

Source: Internet
Author: User

A partial type allows you to define a class, struct, or interface to split into multiple files.

As follows:

In the File1.cs:

namespace pc{    partialclass  A    {        int0;         void MethodA () {}         Partial void methodc ();    }}

In File2.cs, declare:

namespace pc{    partialclass  A    {        void  MethodB () {}         Partial void methodc () {}     }}

When working with large projects or automatically generated code, such as the code provided by the Windows Forms Designer, it can be useful to split the classification, structure, or interface types among multiple files. Partial types can contain partial methods.

Partial (method) (C # Reference)

A partial method defines its signature in one part of a partial type and defines its implementation in another part of the type. Class designers can use partial methods to provide a method hook (similar to an event handler) that the developer decides whether to implement. If the developer does not provide an implementation, the compiler will remove the signature at compile time. The following conditions apply to partial methods:

  • The signatures in the two parts of a partial type must match.

  • Method must return void.

  • There are no allowed access modifiers. The partial method is implicitly private.

    The following example shows a partial method that is defined in the two parts of a partial class:

    namespacepm{Partial classA {Partial voidOnsomethinghappened (strings); }    //This is the can in a separate file.    Partial classA {//Comment out this method and the program//would still compile.        Partial voidonsomethinghappened (String s) {Console.WriteLine ("Something happened: {0}", s); }    }}
Partial Classes and Methods (C # Programming Guide)

You can split the definition of a class or struct, interface, or method into two or more source files. Each source file contains a part of a type or method definition, and all parts are combined when the application is compiled.

Partial class

You need to split the classification definition in the following situations:

    • When working with large projects, having a class spread across separate files allows multiple programmers to process the class at the same time.

    • When you use an automatically generated source, you can add code to the class without recreating the source files. Visual Studio uses this method when creating Windows forms, Web service wrapper code, and so on. You can create code that uses these classes without modifying the files created by Visual Studio.

    • To split a classification definition, use the partial keyword modifier, as follows:

 Public Partial class employee{    publicvoid  DoWork ()    {    }}public  Partialclass  employee{    publicvoid  gotolunch ()    {    }}

partialKeyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All parts must use partial keywords. At compile time, each part must be available to form the final type. Each part must have the same accessibility, such as public , and private so on.

If any part is declared abstract, the entire type is considered abstract. If any part is declared as sealed, the entire type is considered sealed. If any part declares a base type, the entire type inherits the class.

Specifies that all parts of the base class must be consistent, but the part that ignores the base class still inherits the base type. Each section can specify a different base interface, and the final type will implement all of the interfaces listed by all the partial declarations. Any class, struct, or interface member declared in a partial definition can be used by all other parts. The final type is the combination of all the parts at compile time.

Note: partial modifiers are not available in delegate or enumeration declarations.

The following example shows that a nested type can be partial, even if the type that they are nested in is not part of the division itself.

class container{    partialclass  Nested    {        void  Test () {}    }     Partial class Nested    {        void  Test2 () {}}    }

The properties that are defined by the partial type are merged at compile time. Take the following declaration as an example:

[SerializableAttribute] Partial class Moon {}[obsoleteattribute] Partial class Moon {}

They are equivalent to the following declarations:

[Serializableattribute][obsoleteattribute] class Moon {}

The following will be merged from all the partial type definitions:

    • XML annotations

    • Interface

    • Generic type parameter Properties

    • Class characteristics

    • Members

      Take the following declaration as an example:

Partial class earth:planet, irotate {} Partial class Earth:irevolve {}

They are equivalent to the following declarations:

class Earth:planet, Irotate, Irevolve {}
Limit

There are several rules that you should follow when working with partial class definitions:

    • All partial type definitions that are to be part of the same type must be partial decorated using. For example, the following class declaration generates an error:

 Public Partial class A {} // Public class A {}   // Error, must also be marked partial
  • partialModifiers can only appear in class struct the position immediately above the keyword, or in interface front of it.

  • Nested partial types are allowed in the partial type definition, as shown in the following example:

  • Partial class classwithnestedclass{    partialclass  NestedClass {}}partial  Class  classwithnestedclass{    partialclass  NestedClass {}}
  • All partial type definitions that are to be parts of the same type must be defined in the same assembly and in the same module (. exe or. dll file). A partial definition cannot span multiple modules.

  • The class name and generic type parameters must match in all partial type definitions. A generic type can be partial. Each partial declaration must use the same parameter name in the same order.

  • The following keywords used in the partial type definition are optional, but if a keyword appears in a partial type definition, the keyword cannot conflict with a keyword that is specified in another partial definition of the same type:

    • Public

    • Special

    • be protected

    • Internal

    • Abstract

    • Sealed

    • Base class

    • New modifier (nested part)

    • Generic constraints

  • Example 1 describes

    The following example declares a class's fields and constructors in one partial class definition and CoOrds declares a member in another partial class definition PrintCoOrds .

    Code

     Public Partial classcoords{Private intx; Private inty;  PublicCoOrds (intXinty) { This. x =x;  This. y =y; }} Public Partial classcoords{ Public voidPrintcoords () {Console.WriteLine ("CoOrds: {0},{1}", x, y); }}classtestcoords{Static voidMain () {CoOrds mycoords=NewCoOrds (Ten, the);        Mycoords.printcoords (); //Keep the console window open in debug mode.Console.WriteLine ("Press any key to exit.");    Console.readkey (); }}//output:coords:10,15
    Example 2 describes

    As you can see from the example below, you can also develop partial structures and interfaces.

    Code

    Partial Interface itest{    void  interface_test ();} Partial Interface itest{    void  interface_test2 ();} Partial struct s1{    void  struct_test () {}}partialStruct  s1{     void Struct_test2 () {}}
    Partial methods

    Partial classes or structs can contain partial methods. A part of the class contains the signature of the method. You can define an optional implementation in the same section or in another section. If the implementation is not provided, the method and all calls to the method are deleted at compile time.

    A partial method enables implementers of a part of a class to define a method (similar to an event). The implementers of another part of the class can decide whether to implement the method. If the method is not implemented, the compiler deletes the method signature and all calls to the method. Calling the method, including any parameters in the call, evaluates to no effect at run time. Therefore, any code in a partial class can use the partial method arbitrarily, even if the implementation is not provided. Calling but not implementing the method does not result in a compile-time error or a run-time error.

    Partial methods are particularly useful when customizing generated code. These methods allow the method name and signature to be preserved, so the generated code can invoke the method, and the developer can decide whether to implement the method. Very similar to partial classes, partial methods enable code generator-created code and developer-created code to work together without generating runtime overhead.

    A partial method declaration consists of two parts: definition and implementation. They can be in different parts of a partial class, or they can be in the same section. If no implementation declaration exists, the compiler optimizes the definition declaration and all calls to the method.

     //  Definition in File1.cs  partial  void    Onnamechanged ();  //  implementation in File2.cs  partial  void   Onnamechanged () { //  method body }
       
      • A partial method declaration must begin with the context keyword partial, and the method must return void.

      • A partial method can have a ref parameter, but cannot have an out parameter.

      • The partial method is an implicit private method and therefore cannot be a virtual method.

      • A partial method cannot be an extern method, because the presence of the principal determines whether the method is defined or implemented.

      • Partial methods can have static and unsafe modifiers.

      • The partial method can be generic. Constraints are placed on the definition of partial method declarations, but you can also choose to repeat them on the implementation declaration. parameter and type parameter names do not have to be the same in implementation declarations and definition declarations.

      • You can generate a delegate for a partial method that you have defined and implemented, but you cannot generate a delegate for a partial method that has already been defined but not implemented.

    Partial (type) (C # Reference)

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.