2013-08-26 29 views
3

字典我想實現一個字典的包裝類,將類型映射到該類型的泛型列表。例如:<類型,列表字典<Type>>

**Key**    **Value** 
typeof(InterfaceA), List<InterfaceA> 
typeof(InterfaceB), List<InterfaceB> 
typeof(MyClass), List<MyClass> 
... 

然後我想通過使用類型與包裝類進行交互。

public void NewEntry<T>() 
{ 
    MyDict.Add(typeof(T), new List<T>()); 
} 

public List<T> GetEntry<T>() 
{ 
    return MyDict[typeof(T)]; 
} 

public void RemoveEntry<T>() 
{ 
    MyDict.Remove(typeof(T)); 
} 

是否有任何優雅的方式來做到這一點?

編輯:澄清,這點是如此,隨着

GetEntry<MyInterface>() 

在列表中的項目,保證遵守MyInterface的合同。每個條目將具有不同的類型鍵,並且每個項目列表將遵循該類型的合同。

+0

僅靜態。 – SLaks

回答

1

您可以使用下面的靜態類

public static class GenericLists 
{ 
    private static Dictionary<Type, object> MyDict = new Dictionary<Type, object>(); 
    public static void NewEntry<T>() 
    { 
     MyDict.Add(typeof(T), new List<T>()); 
    } 

    public static List<T> GetEntry<T>() 
    { 
     return (List<T>)MyDict[typeof(T)]; 
    } 

    public static void RemoveEntry<T>() 
    { 
     MyDict.Remove(typeof(T)); 
    } 

} 

或者你可以使用

public class GenericLists<T> 
{ 
    private Dictionary<Type, List<T>> MyDict = new Dictionary<Type, List<T>>(); 

    public void NewEntry() 
    { 
     MyDict.Add(typeof(T), new List<T>()); 
    } 

    public List<T> GetEntry() 
    { 
     return MyDict[typeof(T)]; 
    } 

    public void RemoveEntry() 
    { 
     MyDict.Remove(typeof(T)); 
    } 
} 

,如果你真的想初始化它,但我想靜會更好地工作。

+0

爲什麼當你將它添加爲新列表時,爲'value * an * object * ()' – I4V

+0

如果數據是靜態的,你可以不做任何強制轉換。看到我的答案。 – SLaks

+0

現在有什麼不同。你只是重複了這個問題。 – I4V

2

如果你願意來存儲靜態的一切,你可以使用類型系統:

static class MyDict { 
    private static class Data<T> { 
     public static readonly List<T> items = new List<T>(); 
    } 
    public static List<T> Get<T>() { return Data<T>.items; } 
    public static void Add<T>(T item) { Data<T>.items.Add(item); } 
} 

注意,這使得它不可能刪除鍵(你不能卸載型),雖然你可以Clear()吧。

1

您也可以將它作爲基於實例的類來實現(請參閱下文),但是我的首選項(如果它適用於您)是在靜態類中使用靜態變量,因爲SLak在「使用類型系統「後。

public class GenericTypeListDictionary 
{ 
    private readonly Dictionary<Type, object> _dictionaryOfLists = new Dictionary<Type, object>(); 

    public List<T> NewEntry<T>() 
    { 
     var newList = new List<T>(); 
     _dictionaryOfLists.Add(typeof(T), newList); 
     return newList; 
    } 

    public List<T> GetEntry<T>() 
    { 
     object value; 

     if (_dictionaryOfLists.TryGetValue(typeof(T), out value)) 
     { 
      return (List<T>)value; 
     } 

     return null; 
    } 

    public void RemoveEntry<T>() 
    { 
     _dictionaryOfLists.Remove(typeof(T)); 
    } 
} 
+2

不要鎖定「類型」對象。而且,只鎖定一種方法是毫無意義的,鎖定值類型更加毫無意義。 – SLaks

+0

我刪除了鎖定命令。它由於我正在進行的一個完全不相關的討論而悄然而至。但是,我不明白當你處理多線程應用程序時,僅鎖定一種方法的說法毫無意義。 – Grax

+1

我的意思是當其他方法修改相同的結構時只鎖定一種方法。這就像在一條人行道的一半建造一道大門。 – SLaks

相關問題