【问题标题】:Assigning property through constructor overloading通过构造函数重载分配属性
【发布时间】:2014-06-15 21:27:25
【问题描述】:

在下面的类中,我想为构造函数1分配colorColor.White;当通过构造函数 2 调用时,应为其分配参数值。但在此过程中,它首先调用构造函数 1,后者又首先将 color 分配为 Color.White,然后然后分配所需的值。

当涉及到许多构造函数并包含对象时,问题就变得合理了。

有没有办法处理这些不必要的步骤?我想我在这里遗漏了一些基本的东西。

public class Image
{
    Texture2D texture;
    Rectangle frame;
    Rectangle offsetBound;
    Color color;
    // Constructor 1
    public Image(Texture2D texture, Rectangle frame, Rectangle offsetBound)
    {
        this.texture = texture;
        this.frame = frame;
        this.offsetBound = offsetBound;
        this.color = Color.White;  // This is irrelevant
    }
    // Constructor 2
    public Image(Texture2D texture, Rectangle frame, Rectangle offsetBound, Color color)
        : this(texture, frame, offsetBound)
    {
        this.color = color;
    }
}

【问题讨论】:

  • 为什么不让 ctor 1 调用 ctor 2 并传递白色?
  • 听起来不错!我没想到。谢谢!

标签: c# oop constructor


【解决方案1】:

你可以像这样重新排列:

// Constructor 1
public Image(Texture2D texture, Rectangle frame, Rectangle offsetBound)
    : this(texture, frame, offsetBound, Color.White)
{ }

// Constructor 2
public Image(Texture2D texture, Rectangle frame, Rectangle offsetBound, Color color)        
{
    this.texture = texture;
    this.frame = frame;
    this.offsetBound = offsetBound;
    this.color = color;
}

【讨论】:

    【解决方案2】:

    你也可以做下一个,消除第一个构造函数,只留下一个构造函数,这样会提供相同的结果:

    public Image(Texture2D texture, Rectangle frame, Rectangle offsetBound, Color? col = null)
    {
        this.color = col ?? Color.White;
        this.texture = texture;
        this.frame = frame;
        this.offsetBound = offsetBound;
    }
    

    通过使用可选参数,您可以获得与使用 2 个 ctor 相同的结果,如果用户不想提供颜色,只需不要提供颜色,它将被放置为 Color.White 的默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多