当我尝试使用APN构建内容时,我看到了这个代码块.有人可以解释一下,"这个"陈述是做什么的吗?
public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
: this(pushChannelFactory, channelSettings, default(IPushServiceSettings))
Run Code Online (Sandbox Code Playgroud)
它是否像那些参数的默认值?
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)
{
}
Run Code Online (Sandbox Code Playgroud)
这允许您调用一个可以调用另一个的构造函数.
当然 - 将一个构造函数链接到另一个构造函数.有两种形式 - this链接到同一个类中的另一个构造函数,并base链接到基类中的另一个构造函数.您正在链接的构造函数的主体执行,然后执行构造函数体.(当然,其他构造函数可能首先链接到另一个构造函数.)
如果没有指定任何内容,它会自动链接到基类中的无参数构造函数.所以:
public Foo(int x)
{
// Presumably use x here
}
Run Code Online (Sandbox Code Playgroud)
相当于
public Foo(int x) : base()
{
// Presumably use x here
}
Run Code Online (Sandbox Code Playgroud)
请注意,实例变量初始值设定项在调用其他构造函数之前执行.
令人惊讶的是,C#编译器没有检测到你是否以相互递归结束 - 所以这段代码是有效的,但最终会出现堆栈溢出:
public class Broken
{
public Broken() : this("Whoops")
{
}
public Broken(string error) : this()
{
}
}
Run Code Online (Sandbox Code Playgroud)
(但它会阻止您链接到完全相同的构造函数签名.)
有关更多详细信息,请参阅有关构造函数链接的文章.