2012-07-17 109 views
1

继承一个类的所有单身我有以下情形:把那通过反射

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. 
} 

所以我想,以填补字典,通过反射运行时间。 我的朋友可以吗?

在此先感谢!

+0

为什么你想/需要每个类类型的单身人士? – 2012-07-17 16:17:18

+0

不幸的是我们正在使用的类模型。目前无法更改。 – 2012-07-17 16:20:21

+0

是否有可能将此字典添加到基类“Animal”,在创建单例时(从派生类中)同步它,然后公开它? – 2012-07-17 16:24:11

回答

3

本质:

var types = myAssembly.GetTypes(t => typeof(Animal).IsAssignableFrom(t) && !t.IsAbstract); 
var instances = types.Select(t => t.GetProperty("Instance", B.Static).GetValue(null, null)); 
+0

非常好的解决方案 – OnResolve 2012-07-17 16:28:06

+0

几乎在那里我的朋友,这里我的一个大问题是单身人士本身可能有确切的名称“实例”。它可能会有所不同,因为我没有根据我的OO模型对它施加任何限制。 – 2012-07-17 16:37:07

+1

这又是另一个单身人士愚蠢的例子。在一些地方我们有“当前”和“当前域”和“实例”等废话。某处你必须指定一些东西。这些语言通过接口和虚拟关键字支持多态。使用这些功能并为您的实例获取真正的IoC容器。有很多很棒的C#IoC容器。 – Brannon 2012-07-18 03:53:28

1

虽然可以,反射通常是缓慢的,甚至更慢,当你正在做组装搜索。你可以使用元数据(一些像XML这样的DSL)来实现你想要的配置吗?

如果你还是想反映,这将归结到这些步骤(伪代码):

  • 让您执行大会
  • 从装配
  • 获取模块获取从类型模块where type.BaseType == typeof(动物)
  • 一旦你有这些类型,你需要创建它们。如果删除单件部件,则可以调用Instance方法,可以使用激活器(activator API)创建类型。无论哪种方式,你得到你的Animal