在具有多个构造函数的单个类中使用对象

时间:2018-01-12 11:06:00

标签: c# class oop constructor xna

这是我构建构造函数的类,我希望有多个“UserKeys”构造函数,我的项目中的每个字符都有1个但是主类只识别第二个构造函数(如果我有的话)一个带0个参数的构造函数,它识别出第一个,但不识别第二个参数)

abstract class BaseKeys
{
    public abstract bool LeftPressed();
    public abstract bool RightPressed();
    public abstract bool UpPressed();
    public abstract bool DownPressed();
    public abstract bool high_hitPressed();
    public abstract bool rope_jumpPressed();
    public abstract bool runRightPressed();
    public override bool leftRightPressed();
}

class UserKeys : BaseKeys
{
    #region data
    Keys left, right, up, down, walk;
    Keys combo, high_hit;
    #endregion

    #region ctor
    public UserKeys(Keys left, Keys right,
                    Keys up, Keys down, Keys high_hit)
    {
        this.left = left;
        this.right = right;
        this.up = up;
        this.down = down;
        this.high_hit = high_hit;
    }

    public UserKeys(Keys right, Keys left, 
                    Keys down, Keys walk, Keys high_hit)
    {
        this.left = left;
        this.right = right;
        this.down = down;
        this.high_hit = high_hit;
        this.walk = walk;
    }
}

1 个答案:

答案 0 :(得分:3)

两个构造函数具有相同的参数,但不起作用。只有他们的名字不同。你需要让它们与众不同:

public UserKeys(Keys left, Keys right,
                Keys up, Keys down, 
                Keys high_hit)
{
    this.left = left;
    this.right = right;
    this.up = up;
    this.down = down;
    this.high_hit = high_hit;
}

public UserKeys(Keys left, Keys right, 
                Keys up, Keys down, 
                Keys high_hit, Keys walk)
{
    this.left = left;
    this.right = right;
    this.up = up;
    this.down = down;
    this.high_hit = high_hit;
    this.walk = walk;
}

我已将Keys up添加到第二个并使用与第一个相同的顺序(否则非常容易混淆且容易出错)。如果您不知道Keys up通过Keys.None