需要C#构造函数语法解释

有人可以向我解释以下构造函数语法。 我以前没遇到它,并在同事代码中注意到它。

public Service () : this (Service.DoStuff(), DoMoreStuff()) { } 

它链接到同一个类中的另一个构造函数。 基本上任何构造函数都可以使用: this (...)链接到同一个类中的另一个构造函数, 或者使用: base(...)到基类中的构造函数。 如果你没有,它相当于: base()

链接的构造函数在执行实例变量初始化程序之后构造函数的主体之前执行。

有关更多信息,请参阅有关构造函数链接的文章或有关C#构造函数的MSDN主题 。

例如,请考虑以下代码:

 using System; public class BaseClass { public BaseClass(string x, int y) { Console.WriteLine("Base class constructor"); Console.WriteLine("x={0}, y={1}", x, y); } } public class DerivedClass : BaseClass { // Chains to the 1-parameter constructor public DerivedClass() : this("Foo") { Console.WriteLine("Derived class parameterless"); } public DerivedClass(string text) : base(text, text.Length) { Console.WriteLine("Derived class with parameter"); } } static class Test { static void Main() { new DerivedClass(); } } 

Main方法在DerivedClass调用无参数构造DerivedClass 。 它链接到DerivedClass的单参数构造DerivedClass ,然后链接到BaseClass的双参数构造函数。 当该基础构造函数完成时, DerivedClass的单参数构造DerivedClass继续,然后当完成时,原始无参数构造函数继续。 所以输出是:

 Base class constructor x=Foo, y=3 Derived class with parameter Derived class parameterless 

在这种情况下,必须有一个第二个构造函数,它将接受两个参数 – Service.DoStuff()DoMoreStuff()的返回值。 这两种方法必须是静态方法。