繁体   English   中英

如何避免使用多个构造函数重复代码?

[英]How to avoid duplicating code with multiple constructors?

我需要多个类构造函数的帮助。 我不想重复我的代码,但是如何?

    public EventModel(string name, DateTime startTime, DateTime endTime)
        : base(name)
    {
        StartTime = startTime;
        EndTime = endTime;
    }

    public EventModel(Guid id, string name, DateTime startTime, DateTime endTime)
        : base(id, name)
    {
        StartTime = startTime;
        EndTime = endTime;
    }

我看起来像这样:

    public EventModel(Guid id, string name, DateTime startTime, DateTime endTime)
        : this(name, startTime, endTime), base(id, name)
    {
    }

通常在这种情况下,我会将代码重构为通用方法,这样做的缺点是您无法设置readonly字段。

public EventModel(string name, DateTime startTime, DateTime endTime)
    : base(name)
{
    Initialize(startTime, endTime);
}

public EventModel(Guid id, string name, DateTime startTime, DateTime endTime)
    : base(id, name)
{
    Initialize(startTime, endTime);
}

private void Initialize(DateTime startTime, DateTime endTime)
{
    StartTime = startTime;
    EndTime = endTime;
}

如果您可以修改基类以接受可为空的Guid ,则可以将id参数设为可选:

public EventModel(
   string name,
   DateTime startTime,
   DateTime endTime,
   Guid? id = null)
    : base(name, id)
{
   StartTime = startTime;
   EndTime = endTime;
}

然后在您的基类中,将 null id视为与仅采用name的构造函数相同。 这样做可能会阻止您避免在基类中重复,但同时您可以减少基类中的重复。

另外,我强烈建议您将Guid类型参数称为guid 缩短为id几乎没有任何好处,而且更有可能使那些稍后查看代码的人感到困惑和减慢速度。

为构造函数提供默认值。

    public EventModel(Guid id = default(Guid), string name = "Default", DateTime startTime = new DateTime(0), DateTime endTime = new DateTime(0))
    : base(id, name)
{
    StartTime = startTime;
    EndTime = endTime;
}

让基类像这样实现。 下面只是一个例子

基类

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

样品使用

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM