您將需要使用泛型。最簡單的方法是使這種方法通用。你會遇到的一個問題是你必須有一個公共無參數的構造函數。
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