【问题标题】:C# new array. Class with constructorC# 新数组。带构造函数的类
【发布时间】:2017-02-08 05:19:22
【问题描述】:

我在 Unity 工作,但我想这同样适用于 C#。

这是我做的一门课:

    public class KeyboardInput
    {
        private string name;
        private KeyCode btn;

        public KeyboardInput(string buttonName, KeyCode button)
        {
            name = buttonName;
            btn = button;
        }
    }

当我创建类的实例时,如果没有指定构造函数需要的值,会报错。

现在我想创建一个类的数组,我想指定值,但是如何?

如果不指定值,这似乎工作正常

    public class InputController
    {
        private KeyboardInput[] defaultKeyBinding = new KeyboardInput[4];

        public InputController()
        {
            for (int i = 0; i < defaultKeyBinding.Length; i++)
            {
                //Something inside here
            }
        }
    }

我可以调整代码以便能够在 for 循环中设置值,但我很想知道是否有办法!

【问题讨论】:

  • 你的意思是defaultKeyBinding[i] = new KeyboardInput(string, KeyCode)
  • 您应该为每个 KeyboardInput 数组项创建一个新实例。
  • 我很困惑——你想在初始化数组时创建实例还是在构造函数中创建实例?构造函数需要的值从哪里来?你现在遇到什么样的错误?

标签: c# arrays class constructor instance


【解决方案1】:

线

private KeyboardInput[] defaultKeyBinding = new KeyboardInput[4];

只是声明一个数组,还没有初始化任何内容。在你的循环中,你可能想要这样的东西。

for (int i = 0; i < defaultKeyBinding.Length; i++)
{
    //should look something like this
    defaultKeyBinding[i] = new KeyboardInput("Ayy", KeyCode.A);
}

【讨论】:

  • 谢谢。正是我想要的!
【解决方案2】:

这样的事情可以让你在不使用 for 循环的情况下将你的对象放入数组中:

KeyboardInput[] defaultKeyBinding = new KeyboardInput[4];
defaultKeyBinding[0] = new KeyboardInput("someName", KeyCode.A);
defaultKeyBinding[1] = new KeyboardInput("someName2", KeyCode.B);

但是,为了避免在构造函数中未指定参数值时发生的错误,您可以使用可选值。请参阅this page 上的示例。在您的情况下,我不知道为这些参数分配默认值是否有意义,但它看起来像这样:

public KeyboardInput(string buttonName = "defaultButtonName", KeyCode button = KeyCode.A)
{
  name = buttonName;
  btn = button;
}

【讨论】:

  • 感谢您的回答。我不想绕过 for 循环。但你的回答很有帮助!
【解决方案3】:
  KeyboardInput[] array = new KeyboardInput[]
  {
    new KeyboardInput("a",b),
    new KeyboardInput("a", b),
    new KeyboardInput("a", b)
  }

【讨论】:

  • 请解释与问题相关的答案。不要只是发布代码。
猜你喜欢
  • 2015-06-30
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
相关资源
最近更新 更多