初始化对象数组中的对象的正确方法,以便我不会获得空指针引用?



我收到一个空指针异常,我把它缩小到这一小块代码。我认为这是因为当我设置teamStats[iterator].median = Statistics.median时,它不能,因为它还没有初始化。虽然我不知道初始化对象数组的正确方法,也不知道这段代码将导致的内存分支。

下面是我处理的大部分代码,除了描述TeamStat的类,但我已经使用了下面的所有成员,它们是public double

        TeamStat[] teamStats = new TeamStat[DistCount+1];
        int iterator = 0;
        foreach (int i in TeamIDlist)
        {
            var p = userList.Where(x => x.TeamId.Equals(i)).Select(y => (double)y.BS).ToArray();
            var statistics = new DescriptiveStatistics(p);
            teamStats[iterator].median = Statistics.Median(p);
            teamStats[iterator].largestElement = statistics.Maximum;
            teamStats[iterator].smallestElement = statistics.Minimum;
            teamStats[iterator].mean = statistics.Mean;
            teamStats[iterator].variance = statistics.Variance;
            teamStats[iterator].stdDev = statistics.StandardDeviation;
            iterator++;
        }

这是正确的方法吗?

            TeamStat[] teamStats = new TeamStat[DistCount];
        int iterator = 0;
        foreach (int i in TeamIDlist)
        {
            //Added these two lines
            TeamStat temp = new TeamStat();
            teamStats[iterator] = temp;

            var p = userList.Where(x => x.TeamId.Equals(i)).Select(y => (double)y.BS).ToArray();
            var statistics = new DescriptiveStatistics(p);
            teamStats[iterator].median = Statistics.Median(p);
            teamStats[iterator].largestElement = statistics.Maximum;
            teamStats[iterator].smallestElement = statistics.Minimum;
            teamStats[iterator].mean = statistics.Mean;
            teamStats[iterator].variance = statistics.Variance;
            teamStats[iterator].stdDev = statistics.StandardDeviation;
            iterator++;
        }

这里

TeamStat[] teamStats = new TeamStat[DistCount+1];

初始化数组。此时,数组包含DistCount + 1 null条目。

如果你想让数组包含DistCount + 1新的TeamStat项,你需要在循环中初始化它们:

TeamStat[] teamStats = new TeamStat[DistCount+1];
for (var i = 0; i < DistCount + 1; i++)
    teamStats[i] = new TeamStat();

你的代码有两个问题1) Array中的每个对象在访问其属性之前都需要初始化teamStats[iterator] = new TeamStat();2)你需要确保你初始化的数组相同/更多的容量,因为你试图赋值给。(TeamIDlist & lt;discount +1),否则会抛出index out of range异常

相关内容

  • 没有找到相关文章