[Note: The this(?) form of constructor initializer is commonly used in
conjunction with overloading to
implement optional instance constructor parameters. In the example
class Text
{
public Text(): this(0, 0, null) {}
public Text(int x, int y): this(x, y, null) {}
public Text(int x, int y, string s) {
// Actual constructor implementation
}
}
the first two instance constructors merely provide the default values for
the missing arguments. Both use a
this(?) constructor initializer to invoke the third instance constructor,
which actually does the work of
initializing the new instance. The effect is that of optional constructor
parameters:
Text t1 = new Text(); // Same as Text(0, 0, null)
Text t2 = new Text(5, 10); // Same as Text(5, 10, null)
Text t3 = new Text(5, 20, "Hello");
end note]
conjunction with overloading to
implement optional instance constructor parameters. In the example
class Text
{
public Text(): this(0, 0, null) {}
public Text(int x, int y): this(x, y, null) {}
public Text(int x, int y, string s) {
// Actual constructor implementation
}
}
the first two instance constructors merely provide the default values for
the missing arguments. Both use a
this(?) constructor initializer to invoke the third instance constructor,
which actually does the work of
initializing the new instance. The effect is that of optional constructor
parameters:
Text t1 = new Text(); // Same as Text(0, 0, null)
Text t2 = new Text(5, 10); // Same as Text(5, 10, null)
Text t3 = new Text(5, 20, "Hello");
end note]
本文探讨了使用构造函数初始化器实现可选实例构造参数的方法。通过重载构造函数并使用 this 调用,可以为缺少的参数提供默认值,从而简化对象创建过程。
599

被折叠的 条评论
为什么被折叠?



