我有以下情况:
class Cow : Animal
{
public int animalID;
private static Cow instance;
public static Cow Instance
{
get
{
if (instance == null) instance = new Cow();
return instance;
}
}
private Cow() { }
}
Cow
是一个继承自 的普通单例Animal
。我需要的是:aDictionary<int, Animal>
包含从 type 继承的所有单例Animal
,这样,a)列表首先填充所有现有的单例 [已经实例化],以及 b)添加到我的字典中尚未实例化的项的方法。
对于已实现的 Cow、Goat 和 Zebra 类,我想要这种行为:
public class Cow : Animal { ... }
public class Goat : Animal { ... }
public class Zebra : Animal { ... }
public static class AnimalManagement
{
static Dictionary<int, Animal> zoo = new Dictionary<int, Animal>();
static void FillDictionary();
static Animal GetAnimalID(int animalID);
}
public Main()
{
var a1 = Cow.Instance;
var a2 = Goat.Instance;
AnimalManagement.FillDictionary();
// Now, zoo.Count() == 2
// Suppose I seeking for Zebra, with animalID == 5:
Animal zebra = AnimalManagement.GetAnimalID(5);
// Thus, zoo.Count() == 3 and zeebra singleton was
// instantiated and added to internal dic of AnimalManagement.
}
所以我想通过反射在运行时填写字典。我的朋友可以吗?
提前致谢!