C# 类构造与静态成员深入解析
构造函数链与可选参数
在 C# 中,构造函数链是一种实用的技术。以 Motorcycle 类为例:
class Motorcycle
{
public int driverIntensity;
public string driverName;
// Constructor chaining.
public Motorcycle() {}
public Motorcycle(int intensity)
: this(intensity, "") {}
public Motorcycle(string name)
: this(0, name) {}
// This is the 'master' constructor that does all the real work.
public Motorcycle(int intensity, string name)
{
if (intensity > 10)
{
intensity = 10;
}
driverIntensity = intensity;
driverName = name;
}
}
使用 this 关键字进行构造函数链调用并非强制要求,但使用该技术能使类定义更易于维护和简洁。其工作流程如下:
1. 调用需要单
超级会员免费看
订阅专栏 解锁全文
418

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



