2017-02-21 21 views
0

我有一個類,帶有一些全局字典和常量字典。喜歡:C#將靜態字典分配給靜態類中其他字典的已過濾版本

public static class Constants 
{ 
    public static Dictionary<string, MyObject> MyDictionary= new Dictionary<string, MyObject>() 
    { 
     {"first", new MyObject()}, 
     {"second", new MyObject()}, 
    }; 
} 

可以說我想要另一個字典,就像那只有一些添加和刪除的元素。有沒有辦法在靜態類中實現這一點?我想像這樣:

public static Dictionary<string, MyObject> MyOtherDictionary = MyDictionary.Remove("second").Add("Third", new MyObject()) 

但我知道這是行不通的,那麼有什麼辦法可以實現這一目標嗎?

+0

['Remove'(https://msdn.microsoft.com/en-us/library/kabs04ac(V = vs.110)的.aspx)的回報做一個'bool',你不能使用bool添加' –

回答

2

沒有,這樣是行不通的,原因有二:

  1. Remove返回bool,你不能在布爾使用Add
  2. 即使你把它編譯,你不要修改的其他字典,而是要創建一個包含類似項目一個新的字典,您可以使用構造:

public static Dictionary<string, MyObject> MyOtherDictionary; 
// ... 
static Constants 
{ 
    MyOtherDictionary = new Dictionary<string, MyObject>(MyDictionary); 
    MyOtherDictionary.Remove("second"); 
    MyOtherDictionary.Add("Third", new MyObject()); 
} 
+0

謝謝!我不知道爲什麼我沒有意識到這一點。 – Niklas

1

你可以使用屬性,而不是

public static class Constants 
{ 
    public static Dictionary<string, MyObject> myDictionary 
    { 
     get 
     { 
      return new Dictionary<string, MyObject>() 
      { 
       { "first", new MyObject()}, 
       { "second", new MyObject()}, 
      }; 
     } 
    } 

    static Dictionary<string, MyObject> _myOtherDictionary; 
    public static Dictionary<string, MyObject> myOtherDictionary 
    { 
     get 
     { 
      _myOtherDictionary = myDictionary; 
      _myOtherDictionary.Remove("first"); 
      _myOtherDictionary.Add("third", new MyObject()); 
      return _myOtherDictionary; 
     } 
    } 
}