【问题标题】:NullReferenceException was unhandled error with list and randomNullReferenceException 是列表和随机的未处理错误
【发布时间】:2014-05-22 23:59:57
【问题描述】:

我有以下代码示例:

public int intTest { get; set; }
public List<int> listTest { get; set; }

//Method for creating a random number to return.
public int methodRandom()
{
    Random random1 = new Random();
    int intValue;
    intValue = random1.Next(1, intTest + 1);
    return (intValue);
}

private void button1_Click(object sender, EventArgs e)
{
    intTest = int.Parse(textBox1.Text); // Will be a value between 1 and 9 in my code)
    for (int i = 0; i < intTest; i++)
    {
        int temp = methodRandom();
        listTest.Add(temp);
    }
}

但是当我调试并单击按钮时,我收到以下错误消息,标记为“listTest.Add(temp);”说“NullReferenceException 未处理”。我做错了什么?

【问题讨论】:

标签: c# list random nullreferenceexception


【解决方案1】:
private void button1_Click(object sender, EventArgs e)
{
    listTest=new List<int>();
    intTest = int.Parse(textBox1.Text); // Will be a value between 1 and 9 in my code)
    for (int i = 0; i < intTest; i++)
    {
        int temp = methodRandom();

        listTest.Add(temp);
    }
}

【讨论】:

    【解决方案2】:

    您必须先实例化列表,然后才能向其中添加项目。你的构造函数是一个很好的地方。

    public YourClass()  // I don't know what the name of your class is.
    {
        listTest = new List<int>();
    }
    

    您可能也想在每次button1_Click 事件触发时清除列表(除非您的意图只是继续向列表中添加数字)

    private void button1_Click(object sender, EventArgs e)
    {
        listTest.Clear();  // Clear previous items before adding new ones
    
        ...
    }
    

    【讨论】:

    • 这将在每次循环运行时清除列表?所以即使文本框的值大于 1,列表也总是有一个值!所以在这种情况下基本上没有必要列出清单
    • methodRandom() 不是实例化列表的最佳位置;构造函数是个好地方。
    • @GrantWinney 没有问题!
    猜你喜欢
    • 1970-01-01
    • 2015-10-31
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多