简体   繁体   中英

Values in Dictionary keeps changing

A quick describe aboutwhat I need to do as follows:

  • When open an document in Revit, I want to get the id and location of all elements in a Dictionary name _start_state
  • Whenever the document is changed, I want to get the id of the modified elements, then compare them to the keys in _start_state to return the original location from _start_state.

However, the values of the _start_state dictionary is not constant. Everytime CtrlApp_DocumentChanged is called(meaning an element is modified), the values (location) of the corresponding keys(ELementId)in _start_state changes.

        Dictionary<ElementId, Location> _start_state;
        List<ElementId> startKeys;

        public void CtrlApp_DocumentOpened(object sender, DocumentOpenedEventArgs e)
        {
            //Get the current document
            Document doc=e.Document;

            
            IEnumerable<Element> a= GetTrackedElements(doc);

            Dictionary<ElementId, Location> start_state;
            start_state = GetSnapshot(a);

            _start_state = new Dictionary<ElementId, Location>(start_state);
            
            startKeys = _start_state.Keys.ToList();

  
        }


 
         public void CtrlApp_DocumentChanged(object sender, DocumentChangedEventArgs e)        {
                       
            ICollection<ElementId> modifiedElem = e.GetModifiedElementIds();
            
            foreach (ElementId id in modifiedElem)
            {
                if (startKeys.Contains(id))//return new location instead
                {
                    Dictionary<ElementId, Location> dict = new Dictionary<ElementId, Location>();
                    List<Location> locList = new List<Location>();
                    locList.Add(_start_state[id]);
                    
                    foreach (Location loc in locList)
                    {
                        send_baseLocation(loc);
                    }

                    
                }
            }
           }

Do you suggest any way to keep the Dictionary _start_state unchanged over the time? I am thinking about deep cloning or ImmutableDictionary.

Thanks

My guess is Location is a reference type and being mutated when document is changed. Your only option in that case is to clone the location object yourself. ImmutableDictionary won't protect you from properties of Values being mutated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM