有人可以向我解释以下构造函数语法.我以前没遇到它,并在同事代码中注意到它.
public Service () : this (Service.DoStuff(), DoMoreStuff())
{ }
Run Code Online (Sandbox Code Playgroud)
它链接到同一个类中的另一个构造函数.基本上任何构造函数都可以使用链接到同一个类中的另一个构造函数: 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();
}
}
Run Code Online (Sandbox Code Playgroud)
该Main方法调用无参数构造函数DerivedClass.链接到单参数构造函数DerivedClass,然后链接到双参数构造函数BaseClass.当该基类的构造完成,一个参数的构造函数在DerivedClass继续,那么当这完成后,原参数的构造函数继续.所以输出是:
Base class constructor
x=Foo, y=3
Derived class with parameter
Derived class parameterless
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1062 次 |
| 最近记录: |