通过构造函数重载分配属性

Sha*_*wat 0 c# oop constructor

在下面的类,我想分配colorColor.White用于构造1; 当通过构造函数2调用时,应为其分配参数值.但是在这样做时,它首先调用构造函数1,然后构造函数1首先分配coloras 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Blo*_*ard 6

你可以重新安排这样的事情:

// 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;
}
Run Code Online (Sandbox Code Playgroud)