【发布时间】:2014-06-15 21:27:25
【问题描述】:
在下面的类中,我想为构造函数1分配color为Color.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