c#列表对象超出范围.不知道如何处理

本文关键字:何处理 处理 不知道 对象 列表 范围 | 更新日期: 2023-09-27 18:27:50

所以,我有一个简单的C#应用程序。该应用程序允许用户输入测试分数,然后单击"添加"按钮。单击时,文本框内容(如果有效)应进入列表对象。

我当前的代码是说,它是当前上下文中不存在的对象。

private void ScoreCalculatorApplication_Load(object sender, EventArgs e)
    {
        List<int> scoreList = new List<int>();
    }
    private void btn_Add_Click(object sender, EventArgs e)
    {
        scoreList.Add();//this line has the problem
    }

所以,我不确定为什么scoreList不存在,因为ScoreCalculatorApplication_Load方法在加载应用程序时执行。

无论如何,我也考虑过这样的事情:

private void ScoreCalculatorApplication_Load(object sender, EventArgs e)
        {
             //remove this method.
        }
        private void btn_Add_Click(object sender, EventArgs e)
        {
           //is there a test to see if this object exists?
            if (//see if the list does not exist)
                //if not existant, create it here.
            scoreList.Add();
        }

所以,问题是我不知道如何测试对象是否存在。

c#列表对象超出范围.不知道如何处理

这里的问题是,您在比btn_Add_Click更严格的范围内创建scoreList。您在ScoreCalculatorApplication_Load方法的范围内定义了它,这意味着在方法完成后,引用将自动被垃圾收集,并且在该方法之外永远无法访问。

如果希望类中的所有方法都可以访问scoreList对象,则需要创建一个字段或属性。在类范围内,创建并初始化List:

private List<int> scoreList = new List<int>();
private void ScoreCalculatorApplication_Load(object sender, EventArgs e)
{
    /// put whatever else you need to do on loading here
}

scoreList现在可以在类的任何给定实例中访问。请注意,如果您需要其他对象可以访问scoreList,则应将其设置为公共属性,而不是专用字段。

请注意,实际上并没有必要像你所说的那样检查对象是否"存在"——如果你引用了一个不在该范围内的对象或方法,程序将不会编译和运行。如果您愿意,您可以检查scoreList是否已初始化,并可以通过检查它是否为null来填充,例如如果(scoreList==null)。

furkle回答了主要问题。

我只是想回答您的补充问题,现在scoreList在范围内,您可以测试它是否已用if(scoreList==null) 初始化