【问题标题】:Initializing objects of other class?初始化其他类的对象?
【发布时间】:2019-01-15 09:11:46
【问题描述】:

我有一个有 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# list class object


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    你实例化了数组,但没有实例化里面的元素。

    for(int i = 0; i < Entries; i++)
    {
        graphDataPoints[i] = new dataPoints();
        // I removed the lines below because they are already initialized in the constructor
        // graphDataPoints[i].timeStamps = new List<DateTime>();
        // graphDataPoints[i].dataValues = new List<double>();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多