【问题标题】:Using an object in a single class with multiple constructors在具有多个构造函数的单个类中使用对象
【发布时间】:2018-01-12 11:05:59
【问题描述】:

这是我在其中构建构造函数的类,我想要有多个“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;
    }
}

【问题讨论】:

  • 什么是“识别”,你得到一个编译器错误?如果是这样,请告诉我们。 Main 类中使用构造函数的代码是什么?两个构造函数都有相同的参数,这是行不通的。
  • 这是什么意思:“我想要多个“UserKeys”构造函数,每个字符 1 个”?
  • 我的角色很少,蝙蝠侠零下超人和闪电侠。我想在 UserKeys 中为每个从键盘获取不同键的字符设置构造函数,例如,我想通过单击 f 来选择超人飞行,但 flash 不需要这个功能,所以我希望在UserKeys 类,因此我不需要为我从他不使用的键盘构建键的字符提供。在我的主课中,我所做的只是创建新的 UserKeys 对象,我想给它键盘键(例如:上、下、右、左、'Z'、'X')

标签: c# class oop constructor xna


【解决方案1】:

两个构造函数都有相同的参数,这是行不通的。只是他们的名字不同。你需要让它们与众不同:

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

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2016-01-16
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多