【问题标题】:Values in Dictionary keeps changing字典中的值不断变化
【发布时间】:2022-11-27 07:33:19
【问题描述】:

快速描述一下我需要做的事情如下:

  • 在 Revit 中打开文档时,我想获取字典名称 _start_state 中所有元素的 ID 和位置
  • 每当更改文档时,我想获取修改元素的 ID,然后将它们与 _start_state 中的键进行比较以从 _start_state 返回原始位置。

但是,_start_state 字典的值不是常量。每次调用 CtrlApp_DocumentChanged(意味着修改元素)时,_start_state 中相应键(ELementId)的值(位置)都会发生变化。

        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);
                    }

                    
                }
            }
           }

您有什么建议可以使 Dictionary _start_state 随时间保持不变吗?我正在考虑深度克隆或 ImmutableDictionary。

谢谢

【问题讨论】:

    标签: c# dictionary revit-api


    【解决方案1】:

    我的猜测是 Location 是一种引用类型,并且在更改文档时会发生变化。在这种情况下,您唯一的选择是自己克隆位置对象。 ImmutableDictionary 不会保护您免受 Values 属性的影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2011-12-16
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多