美好的一天! 我想知道在实例化类时是否可以分配多种不同类型的参数。
以下是我现在所拥有的一个例子
public Unit(Vector2 Position, Color col)
{
this.position = Position;
this.color = col;
}
注意它是如何同时需要一个Vec2&颜色,我想知道是否可以这样做,所以我可以选择只有一个参数或两个例子如下。
public Unit(Vector2 Position)
{
this.position = Position;
this.color = Color.White;
}
public Unit(Vector2 Position, Color col)
{
this.position = Position;
this.color = col;
}
答案 0 :(得分:4)
如果使用C#4或更新版本,另一种可能性是默认值
public Unit(Vector2 position, Color col = Color.White)
{
this.position = position;
this.color = col;
}
Unit u = new Unit(myVector2); // defaults to white
Unit u2 = new Unit(myVector2, Color.Blue);
答案 1 :(得分:3)
当然你可以完全像那样重载构造函数。我建议让一个重载调用另一个:
public Unit(Vector2 position) : this(position, Color.White)
{
}
public Unit(Vector2 position, Color col)
{
this.position = position;
this.color = col;
}