0
私は自分の論文のために遺伝的アルゴリズムの実装をしようとしています。主なクラスには、染色体としてFacility
と遺伝子としてFacilityCell
があります。しかし、Facility
クラスから適合値を取得する際にエラーが発生します。プロパティ配列に値を設定しようとしたときにNullReferenceExceptionが発生するのはなぜですか?
Form.csに必要な値が設定され、アルゴリズムが実行された後、これらのプロパティはFacility
インスタンスのnull
になります。これらのプロパティはFacility.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
から
コード部分:
public class Facility : IChromosome
{
public Facility()
{
}
public Facility(FacilityCell[] cells)
{
this.cells = cells;
flows = null;
demands = null;
for (int i = 0; i < cells.Length; i++)
{
cells[i].Order = i;
}
}
private IGene[] cells;
private float[] demands;
private FacilityCell[][] flows;
public FacilityCell[][] Flows
{
get { return flows; }
set { flows = value; }
}
public FacilityCell[] Cells
{
get
{
return cells as FacilityCell[];
}
set
{
cells = value;
}
}
public float[] Demands
{
get { return demands; }
set { demands = value; }
}
public float FitValue
{
get
{
float total = 0;
//I AM GETTING ERROR IN THIS LINE OF CODE, THE FOR LOOP
//It throws NullReferenceException for both this.Demands and this.Flows
for (int i = 0; i < flows.Length; i++)
{
for (int j = 0; j < flows[i].Length - 1; j++)
{
int dist = Math.Abs(flows[i][j + 1].Order - flows[i][j].Order);
float totflow = dist * demands[i];
total += totflow;
}
}
return total;
}
}
public IGene[] Genes
{
get
{
return cells;
}
set
{
cells = value;
}
}
}
初期化メンバーは使用前に考慮しましたか? OOPでは、クラスインスタンスを使用可能な状態に初期化するコンストラクタを記述しようとします。あなたが見ることができるように、コンストラクタの外側のランダムな場所で初期化の半分を隠すことは悪い考えです。インスタンスを作成するときに常に実行される1ビットのコードは、コンストラクタです。 Keep It Simple:コンストラクタで初期化すると、 'new'演算子があなたに爆発しないようにすることができます。 –