在这种情况下,bool 数组不会被自动深度复制。因此,您并没有真正从结构中受益,因为当您将 Chromosome 分配给新结构时,两者中的引用将指向同一个 bool[ ]
你可以只使用一个数字而不是使用 bool[]:比如说int。基因= 3的染色体代表基因:0000 0000 0000 0000 0000 0011。基因= 42134的染色体代表基因:0000 0000 1010 0100 1001 0110。int是32位,这意味着您可以用232 基因这样。
您不必担心深度复制数组,这在内存消耗方面也更快、更有效。如果您需要更多基因,请使用 Int64。
更新:
顺便说一句,你的问题太酷了。如果您对某些片段中可能的基因组合有限制,则需要根据限制逐字节构造Int32。为了说明,我假设了一个对染色体的一些限制的例子,并随机突变了一个染色体,但与约束有关。
//The following creates a random chromosome with restrictions
//to the genes as described in the following:
//Let's say that the following pattern must be adhered to:
//byte 1 = xxxx xxxx (anything)
//byte 2 = 1011 xxxx (restricted)
//byte 3 = [0000 or 1111] xxxx (restricted)
//byte 4 = 0000 1111 (fixed value)
Random rnd = new Random();
byte[] randomByte = new byte[1]; //xxxx xxxx xxxx xxxx
byte restrictedByte2 =
(byte)(Math.Pow(2,7) * 1 + Math.Pow(2,6) * 0 +
Math.Pow(2,5) * 1 + Math.Pow(2,4) * 1 +
rnd.Next(0, 16)); //1011 xxxx
//in byte 3, the first (most significant) for bits are restricted to either 0000 or 1111.
//That's either number 0 * 16 = 0 or number 15 * 16 = 240. I multiplied by 2^4 because it's shifted
//4 bytes to the left.
byte higherBits = (byte)(rnd.Next(0, 2/*upper bound exclusive*/) == 1?240:0);
//random lower bits (xxxx).
byte lowerBits = (byte)(Math.Pow(2,0) * rnd.Next(0, 2) + Math.Pow(2,1) * rnd.Next(0, 2) +
Math.Pow(2,2) * rnd.Next(0, 2) + Math.Pow(2,3) * rnd.Next(0, 2) +
rnd.Next(0, 16));
byte restrictedByte3 = (byte)(lowerBits + higherBits);
byte restrictedByte4 = 143; //constant
//Create an Int32 from the four bytes.
int randomMutation = BitConverter.ToInt32(
new byte[] { randomByte[1], restrictedByte2, restrictedByte3, restrictedByte4 }, 0);