Answer the question
In order to leave comments, you need to log in
How are dictionary changes reflected in assignable ones?
let's take 3 dictionaries with the same structure as an example, 1 main one is filled, 2 and 3 are empty, then 2 and 3 are assigned to the 1st dictionary
private Dictionary<string, ClassTest> Dictionary1 = new Dictionary<string, ClassTest>();
private Dictionary<string, ClassTest> Dictionary2 = new Dictionary<string, ClassTest>();
private Dictionary<string, ClassTest> Dictionary3 = new Dictionary<string, ClassTest>();
//Dictionary1 -заполняем данными
Dictionary2 = Dictionary1;
Dictionary3 = Dictionary1;
Answer the question
In order to leave comments, you need to log in
https://docs.microsoft.com/en-us/dotnet/csharp/lan...
as I understand it, if I change the values in Dictionary1, then they will change in 2 and 3 dictionaries?
but if I change the values in 2 and 3 dictionaries, they will not affect each other?
that is, changing the values in the 2nd dictionary will not affect the 3rd dictionary in any way, do I understand correctly?
And it’s just that I recently encountered such a problem that I assigned one dictionary to another Dictionary2 = Dictionary1 then cleared the 1st and the 2nd automaton also turned out to be cleared
private Dictionary<string, ClassTest> Dictionary1 // переменная Dictionary1 типа Dictionary<>
= new Dictionary<string, ClassTest>(); //которая ссылается на объект Dictionary [id=1]
private Dictionary<string, ClassTest> Dictionary2 // переменная Dictionary2 типа Dictionary<>
= new Dictionary<string, ClassTest>(); //которая ссылается на объект Dictionary [id=2]
private Dictionary<string, ClassTest> Dictionary3 // переменная Dictionary3 типа Dictionary<>
= new Dictionary<string, ClassTest>(); //которая ссылается на объект Dictionary [id=3]
//Dictionary1 -заполняем данными
Dictionary2 = Dictionary1; //переменная Dictionary2 теперь ссылается туда-же, куда и переменная Dictionary1,
// т.е на Dictionary [id=1]
Dictionary3 = Dictionary1; //переменная Dictionary3 теперь ссылается туда-же, куда и переменная Dictionary1,
// т.е на Dictionary [id=1]
// a объекты Dictionary [id=2] и Dictionary [id=3] будут собраны сборщиком мусора, т.к. они больше не нужны
But how can I make 2 dictionaries like the 1st, that is, I have the 1st dictionary template, I want the 2nd and 3rd dictionaries to initially look the same (have all the same data), but then the data in them changes independently of each other?
var dict1 = new Dictionary<int, int>()
{
[1] = 2,
};
var dict2 = new Dictionary<int, int>(dict1);
dict1.Add(2, 3);
dict2.Add(2, 1);
var log = new Action<Dictionary<int,int>>((dict) =>
{
Console.WriteLine(string.Join(", ", dict.Select(c => $"{c.Key}={c.Value}")));
});
log(dict1); //1=2, 2=3
log(dict2); //1=2, 2=1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question