继承一个类的所有单身我有以下情形:把那通过反射
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)添加到我的字典项目的方法尚未实例化。
对实现的类牛,山羊和斑马我想这种行为:
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.
}
所以我想,以填补字典,通过反射运行时间。 我的朋友可以吗?
在此先感谢!
为什么你想/需要每个类类型的单身人士? – 2012-07-17 16:17:18
不幸的是我们正在使用的类模型。目前无法更改。 – 2012-07-17 16:20:21
是否有可能将此字典添加到基类“Animal”,在创建单例时(从派生类中)同步它,然后公开它? – 2012-07-17 16:24:11