2012-07-17 72 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