C#/XNA为什么可以';t我添加到数组列表中

本文关键字:添加 数组 列表 XNA 为什么 | 更新日期: 2023-09-27 18:30:13

我在向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);
}

这段特定的代码是由一位讲师提供给我的,我不清楚为什么它不能正常工作。

C#/XNA为什么可以';t我添加到数组列表中

您正试图在方法体之外执行非初始值设定项代码(对ArrayList.Add的调用)。这行不通。

您必须使用集合初始值设定项语法

ArrayList ControllerList = new ArrayList
                               {
                                   new KeyboardController(),
                                   new GamepadController()
                               };

或者在类的构造函数中进行初始化。

另外,如果不需要的话,不要使用ArrayList,而是使用List<IController>

您需要将添加代码行的项放入类构造函数或方法中。

ControllerList = new ArrayList(); 
ControllerList.Add(new KeyboardController());

并且您不能将项添加到未初始化的(null)ArrayList,您只将ControllerList声明为ArrayList,但未初始化