2016-10-16 7 views
-1

に値としてそれを挿入した後、私は次の問題を経験したが、それは一般的な問題である:は、オブジェクトを再利用するコレクション

は、私が持っていると言う:

  1. いくつかのクラス(例えば、Cat)、いくつかのメンバーを含む(例えば、公開Ageプロパティ)。
  2. 一部のキー(たとえば、string)とList<T>の値(例:List<Cat>)を持つHas​​hTableです。

    私が意味
    Hashtable catDictionary = new Hashtable();  
    
    Cat cat1 = new Cat() { Age = 10 }; 
    Cat cat2 = new Cat() { Age = 12 }; 
    List<Cat> catList = new List<Cat>(); 
    catList.Add(cat1); 
    catList.Add(cat2); 
    
    catDictionary["oldCat"] = catList; 
    
    catList.Clear(); // This undesirably clears the list in HashTable["oldCat"] 
    Cat cat3 = new Cat() { Age = 2 }; 
    catList.Add(cat3); // Now the list in HashTable["oldCat"] references a young cat! 
    catDictionary["youngCat"] = catList; 
    

    HashTable["oldCat"]List<cat>への参照は、自身の得ることができます:

List<Cat>の単一のインスタンスをインスタンス化し、それが望ましい方法になりように、それを再利用する方法はあります挿入されたList<Cat>のコピーをコピーして、main内のコピーから「切り離される」ようにしますか?

Catオブジェクトを再利用することについて同じ質問をすることができますが、Listを再利用すると、より便利に感じられます。

+0

は、個々のアイテムを取得するために))(最終、それは)あなたが最初のを(使用する必要が同じリスト –

+0

を参照される他に、新しいリストにCAT3を追加、または(テイク。または、Select/Whereを使用してリストを列挙します。 – jdweng

答えて

0

辞書に挿入するリストは新しいものにする必要があります。そうしないと、メインリストに加えられる変更はすべて辞書に反映されます(基本的に同じインスタンスに2つの参照があるためです)。

私はまた、リストの新しいコピーを作成するために、LINQ ToList() methodを使用して、これを試してみてください
あなたは一般的な辞書を使用することをお勧めの代わりに、Hashtableの
:それはなります

Dictionary<string, List<Cat>> catDictionary = new Dictionary<string, List<Cat>>();  

Cat cat1 = new Cat() { Age = 10 }; 
Cat cat2 = new Cat() { Age = 12 }; 
List<Cat> catList = new List<Cat>(); 
catList.Add(cat1); 
catList.Add(cat2); 

catDictionary["oldCat"] = catList.ToList(); 

catList.Clear(); 
Cat cat3 = new Cat() { Age = 2 }; 
catList.Add(cat3); 
catDictionary["youngCat"] = catList.ToList(); 
0

あなたは、新しいリストを作成する必要があり、そうでありません同じリスト。

Hashtable catDictionary = new Hashtable(); 
Cat cat1 = new Cat() { Age = 10 }; 
Cat cat2 = new Cat() { Age = 12 }; 
List<Cat> catList = new List<Cat>(); 
catList.Add(cat1); 
catList.Add(cat2); 

catDictionary["oldCat"] = new List<Cat>(catList); 

catList.Clear(); // This undesirably clears the list in HashTable["oldCat"] 
Cat cat3 = new Cat() { Age = 2 }; 
catList.Add(cat3); // Now the list in HashTable["oldCat"] references a young cat! 
catDictionary["youngCat"] = catList; 
関連する問題