c# - 初始化其他类的对象?
问题描述
我有一个有 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 类中删除构造函数后,同样的错误仍然存在。
解决方案
您已经创建了一个数组dataPoints
(应该DataPoints
根据 C# 的命名标准调用),但您还没有创建dataPoints
对象本身。数组中的元素都是空的,因此是空引用异常。
因此,在 for 循环中,您应该dataPoints
使用以下命令创建对象new dataPoints()
:
for(int i=0;i<Entries;i++)
{
graphDataPoints[i] = new dataPoints();
}
推荐阅读
- django - 在 django 中发送电子邮件
- python - 如何根据行对数据框进行排序
- mongodb - 计算 mongodb 文档中值的频率
- data-science - Vowpal Wabbit:数据与多通道打乱的数据 - 为什么在学习之前打乱文件有助于提高指标
- swift - 在 main 中使用包中的类
- youtube - 如何让两个人收到 YouTube 评论的通知?
- css - 图像无法显示,因为它包含错误
- android - 如何在 kotlin 中使 Material Button ToggleGroup 的所有子项不可点击
- typescript - 如何深度过滤(搜索)对象?
- ios - 如何将 UIImages 数组从 Firebase 存储目录下载到 Swift?