繁体   English   中英

C# 新数组。 带构造函数的类

[英]C# new array. Class with constructor

我在 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 循环中设置值,但我很想知道是否有办法!

线

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);
}

这样的事情将允许您将对象放入数组中而不使用 for 循环:

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

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

public KeyboardInput(string buttonName = "defaultButtonName", KeyCode button = KeyCode.A)
{
  name = buttonName;
  btn = button;
}
  KeyboardInput[] array = new KeyboardInput[]
  {
    new KeyboardInput("a",b),
    new KeyboardInput("a", b),
    new KeyboardInput("a", b)
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM