2017-02-21 3 views
0

私はいくつかのグローバルで一定の辞書を持つクラスを持っています。 Like:C#静的クラスを静的クラスの他の辞書のフィルタリングされたバージョンに割り当てます

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

私は別の辞書を追加したいと思っています。静的クラス内でそれを達成する方法はありますか?

しかし、私はそれがうまくいかないことを知っているので、これを達成する方法はありますか?

+0

[ 'Remove'](https://msdn.microsoft.com/en-us/library/kabs04ac(V = vs.110).aspxの)リターンをプロパティを使用してそれを行うことができます'bool'、boolに' Add'を使うことはできません –

答えて

2

いいえ、二つの理由から、このようにそのdo​​esntの仕事:

  1. Removeboolを返し、あなたはそれがコンパイルさせる場合でも、そうでないブール
  2. Addを使用することはできませんあなたはコンストラクタを使用することができ、他の辞書を変更したいが、あなたは同様の項目が含まれている新しい辞書を作成したい:

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; 
     } 
    } 
} 
関連する問題