这个语句在构造函数的参数之后

当我尝试使用APN构建内容时,我看到了这个代码块。 有人可以解释一下“这个”陈述是做什么的吗?

public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings) : this(pushChannelFactory, channelSettings, default(IPushServiceSettings)) 

它是否像那些参数的默认值?

this将使用指定的参数调用ApplePushService类的重载构造函数。

例如

 // Set a default value for arg2 without having to call that constructor public class A(int arg1) : this(arg1, 1) { } public class A(int arg1, int arg2) { } 

这允许您调用一个可以调用另一个的构造函数。

当然 – 将一个构造函数链接到另一个构造函数。 有两种forms – this可以链接到同一个类中的另一个构造函数,并且可以链接到基类中的另一个构造函数。 您正在链接的构造函数的主体执行,然后执行构造函数体。 (当然,其他构造函数可能首先链接到另一个构造函数。)

如果您没有指定任何内容,它会自动链接到基类中的无参数构造函数。 所以:

 public Foo(int x) { // Presumably use x here } 

相当于

 public Foo(int x) : base() { // Presumably use x here } 

请注意,实例变量初始值设定项调用其他构造函数之前执行。

令人惊讶的是,C#编译器没有检测到你是否最终相互递归 – 所以这段代码是有效的,但最终会出现堆栈溢出:

 public class Broken { public Broken() : this("Whoops") { } public Broken(string error) : this() { } } 

(但它会阻止您链接到完全相同的构造函数签名。)

有关更多详细信息,请参阅有关构造函数链接的文章 。

那就是在这种情况下调用另一个构造函数, : this(...)用于调用该类中的另一个构造函数。

例如:

 public ClassName() : this("abc") { } public ClassName(string name) { } 

编辑:

Is it like default values of those arguments ?

它是一个重载,你可以在一个地方委托它的完整逻辑,并使用默认值从其余的构造函数调用。

this关键字可用于以下上下文:

  • 打电话给其他建设者。
  • 将当前对象作为参数传递。
  • 请参阅实例方法或字段。