尝试将值设置为属性数组时,为什么会出现NullReferenceException?

时间:2016-04-10 00:12:25

标签: c# arrays winforms properties nullreferenceexception

我正在尝试为我的论文制作遗传算法。主要有两类:1: {3,4,5,6} 2: {1,1,1,2,4,3,4} 3: {6,7,8} 4: {1,1,2,3} 为染色体,Facility为基因。但是我从FacilityCell级获得适应值时遇到错误。

必要的值在Form.cs中设置,运行算法后,Facility实例中的这些属性为null。这些属性为FacilityFacility.Flows。我不明白为什么。请帮忙。

Facility.Demands

的代码部分
Form.cs

来自fac = new Facility(); List<FacilityCell> gens = new List<FacilityCell>(); for (int i = 0; i < 6; i++) { gens.Add(new FacilityCell(i.ToString(), i)); } fac.Genes = gens.ToArray(); fac.Cells = gens.ToArray(); float[] dems = new float[3]; dems[0] = 300; dems[1] = 60; dems[2] = 160; fac.Demands = dems; FacilityCell[][] fl = new FacilityCell[3][]; fl[0] = new FacilityCell[] { fac.Cells[0], fac.Cells[2], fac.Cells[4], fac.Cells[1], fac.Cells[3], fac.Cells[5] }; fl[1] = new FacilityCell[] { fac.Cells[2], fac.Cells[4], fac.Cells[1], fac.Cells[5], fac.Cells[3], fac.Cells[4] }; fl[2] = new FacilityCell[] { fac.Cells[1], fac.Cells[0], fac.Cells[4], fac.Cells[2], fac.Cells[3], fac.Cells[5] }; fac.Flows = fl; 的代码:

Facility.cs

1 个答案:

答案 0 :(得分:1)

此代码:FacilityCell[][] fl = new FacilityCell[3][];将在构造函数集demands中为null,您在设置demands之后调用代码。