首页 > 解决方案 > 初始化其他类的对象?

问题描述

我有一个有 2 个列表的类作为它的数据成员。我想将这些数据成员作为不同的类对象。

我收到此错误:

“你调用的对象是空的。”

请告知应该是正确的方法。

class dataPoints
{
    public List<double> dataValues;
    public List<DateTime> timeStamps;

    public dataPoints()
    {
      this.timeStamps = new List<DateTime>();
      this.dataValues = new List<double>();
    }
}


//I want an object of dataPoints in this below classs
class wellGraph
{
    int seriesAdded;
    dataPoints[] graphDataPoints;

    public wellGraph(int Entries)
    {
        this.seriesAdded = 0;
        this.graphDataPoints = new dataPoints[Entries];

        for(int i=0;i<Entries;i++)
        {
            graphDataPoints[i].timeStamps = new List<DateTime>();
            graphDataPoints[i].dataValues = new List<double>();
        }

    }
}

在 dataPoints 类中删除构造函数后,同样的错误仍然存​​在。

标签: c#listclassobject

解决方案


您已经创建了一个数组dataPoints(应该DataPoints根据 C# 的命名标准调用),但您还没有创建dataPoints对象本身。数组中的元素都是空的,因此是空引用异常。

因此,在 for 循环中,您应该dataPoints使用以下命令创建对象new dataPoints()

for(int i=0;i<Entries;i++)
{
    graphDataPoints[i] = new dataPoints();
}

推荐阅读