我有以下场景:
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 的普通单例. 我需要的是:Dictionary<int, Animal>所有继承自 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.
}
所以我想在运行时通过反射来填充字典。 有可能吗我的 friend 们?
提前致谢!
请您参考如下方法:
本质上:
var types = myAssembly.GetTypes(t => typeof(Animal).IsAssignableFrom(t) && !t.IsAbstract);
var instances = types.Select(t => t.GetProperty("Instance", B.Static).GetValue(null, null));
