C# 多实例参数

C# 多实例参数,c#,C#,你好! 我想知道在实例化一个类时是否可以分配多种不同类型的参数 这是我现在所拥有的一个例子 public Unit(Vector2 Position, Color col) { this.position = Position; this.color = col; } 请注意它是如何同时需要一个Vec2和Color的,我想知道是否可以这样做,这样我就可以在下面的示例中选择一个参数或两个参数 1. 2. 当然可以像那样重载构造函数。不过,我

你好! 我想知道在实例化一个类时是否可以分配多种不同类型的参数

这是我现在所拥有的一个例子

    public Unit(Vector2 Position, Color col)
    {
        this.position = Position;
        this.color = col;
    }
请注意它是如何同时需要一个Vec2和Color的,我想知道是否可以这样做,这样我就可以在下面的示例中选择一个参数或两个参数

1. 2.
当然可以像那样重载构造函数。不过,我建议你打一个超负荷电话给另一个:

public Unit(Vector2 position) : this(position, Color.White)
{
}

public Unit(Vector2 position, Color col)
{
    this.position = position;
    this.color = col;
}

如果您使用的是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,然后在下面写选项2。然后,您可以选择如何创建类的实例(1个或2个参数)。是的,如果有一种方法不需要这堵代码墙,我会考虑更多。它应该是:
public Unit(…):这个(…){…}
这个片段本身,不,因为它不是一个完整的类。但是,如果您使用的是C#4或更高版本,那么上述方法通常是有效的。
public Unit(Vector2 position) : this(position, Color.White)
{
}

public Unit(Vector2 position, Color col)
{
    this.position = position;
    this.color = col;
}
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);