Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c# - Partial Class Constructors

Is there a way to have a partial class' constructor call another method that my or may not be defined?

Basically my partial class constructor is defined:

public partial class Test
{
     public Test()
     {
          //do stuff
     }
}

I would like to be able to somehow insert extra code to be run after the class constructor is called.

In addition, is there a way to have more than one file to inject extra code after the constructor is called?

question from:https://stackoverflow.com/questions/1580509/partial-class-constructors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C# does support the feature of partial methods. These allow a partial class definition to forward declare a method that another part of the partial class can then optionally define.

Partial methods have some restrictions:

  • they MUST be of void type (no return)
  • they CANNOT accept out parameters, they can however accept ref parameters
  • they CANNOT be virtual or extern and CANNOT override or overwrite another method (via "new" keyword)

Partial methods are implicitly sealed and private.

It is not, however, possible, to have two different portions of a partial class implement the same partial method. Generally partial methods are used in code-generated partial classes as a way of allowing the non-generated part of extend or customize the behavior of the portion that is generated (or sometimes vice versa). If a partial method is declared but not implemented in any class part, the compiler will automatically eliminate any calls to it.

Here's a code sample:

 public partial class PartialTestClass
 {
     partial void DoSomething();

     public PartialTestClass() { DoSomething(); }
 }

 public partial class PartialTestClass
 {
     partial void DoSomething()  { /* code here */ }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...