您将需要使用泛型。最简单的方法是使这种方法通用。你会遇到的一个问题是你必须有一个公共无参数的构造函数。
public TOrganism Reproduce<TOrganism>()
where TOrganism : Organism, new()
{
double[] copy = new double[genes.Count];
for(int i = 0; i < copy.Length; i++)
// 10% chance to mutate, change up to 10%
copy[i] = genes[i] + (Program.rand.Next(10) < 1 ?
genes[i] * 0.2 * (Program.rand.NextDouble() - 0.5) : 0.0);
TOrganism child = new TOrganism();
child.Genes = genes;
return child;
}
然后你会这样调用这个方法。
Plant myPlant = new Plant();
Plant newPlant = myPlant.Reproduce<Plant>();
我会更进一步,让这个单独的类,使测试更容易。甚至可能是扩展方法。
public static class OrganismReproducer : IOrganismReproducer
{
public static TOrganism Reproduce<TOrganism>(this TOrganism organism)
where TOrganism : Organism, new()
{
double[] copy = new double[organism.Genes.Count];
for(int i = 0; i < copy.Length; i++)
// 10% chance to mutate, change up to 10%
copy[i] = genes[i] + (Program.rand.Next(10) < 1 ?
genes[i] * 0.2 * (Program.rand.NextDouble() - 0.5) : 0.0);
TOrganism child = new TOrganism();
child.Genes = genes;
return child;
}
}
然后你可以这样调用它。
Plant myPlant = new Plant();
Plant newPlant = myPlant.Reproduce();
// no need to specify generic type parameter
// it is inferred based on the type of myPlant
谢谢我正在与第一个选项。 – MrFox 2012-02-11 12:48:33