C# 新数组。 Class 与构造函数
C# new array. Class with constructor
我在 Unity 工作,但我想这同样适用于 C#。
这是class我做的:
public class KeyboardInput
{
private string name;
private KeyCode btn;
public KeyboardInput(string buttonName, KeyCode button)
{
name = buttonName;
btn = button;
}
}
当我创建 class 的实例时,如果我没有指定构造函数所需的值,我将得到一个错误。
现在我想创建一个 class 的数组,我想指定值,但是如何?
这似乎在不指定值的情况下工作正常
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);
但是,为了避免在构造函数中没有为参数指定值时出现错误,您可以使用可选值。请参阅 this page 上的示例。在你的情况下,我不知道为这些参数分配默认值是否有意义,但它看起来像这样:
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)
}
我在 Unity 工作,但我想这同样适用于 C#。
这是class我做的:
public class KeyboardInput
{
private string name;
private KeyCode btn;
public KeyboardInput(string buttonName, KeyCode button)
{
name = buttonName;
btn = button;
}
}
当我创建 class 的实例时,如果我没有指定构造函数所需的值,我将得到一个错误。
现在我想创建一个 class 的数组,我想指定值,但是如何?
这似乎在不指定值的情况下工作正常
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);
但是,为了避免在构造函数中没有为参数指定值时出现错误,您可以使用可选值。请参阅 this page 上的示例。在你的情况下,我不知道为这些参数分配默认值是否有意义,但它看起来像这样:
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)
}