[英]C#/XNA Why can't I add to the Array List?
我在将对象添加到ArrayList时遇到了一些麻烦。 当尝试将KeyboardController()和GamepadController()添加到ArrayList时,我被告知ControllerList是一个字段,但是它被用作一种类型。 这两个类都实现了接口IController。 此外,有人告诉我KC()和GC()都必须具有返回类型。 任何人都可以让我知道导致问题的原因。 有没有更合适的方法?
// Initialization
ArrayList ControllerList;
ControllerList.Add(new KeyboardController()); //error
ControllerList.Add(new GamepadController()); //error
IAnimatedSprite MarioSprite = new SmallMarioRunningRightSprite();
protected override void Update(GameTime gameTime)
{
foreach(IController Controller in ControllerList)
{
Controller.Update();
}
MarioSprite.Update();
base.Update(gameTime);
}
这部分特定的代码是由一位教师提供给我的,我不清楚为什么它无法正常运行。
您需要将添加代码行的项目放在类构造函数或方法中。
ControllerList = new ArrayList();
ControllerList.Add(new KeyboardController());
并且您也不能将项添加到未初始化( null
)的ArrayList中,您只将ControllerList
声明为ArrayList
而不初始化。
您试图在方法主体之外执行非初始化程序代码(对ArrayList.Add
的调用)。 这行不通。
您必须使用集合初始化器语法
ArrayList ControllerList = new ArrayList
{
new KeyboardController(),
new GamepadController()
};
或在类的构造函数中进行初始化。
另外,如果不需要,请不要使用ArrayList
。 使用List<IController>
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.