Word VSTO中注释RCW指向错误的异常行为咨询
问题原因
这是Word对象模型(COM互操作)的特性导致的,并非代码bug。Word的Comment对象是动态绑定到文档内容的,而非静态的独立实例:
- 当你在同一文本范围添加新注释时,Word默认会覆盖原有注释(操作时会弹出替换提示),原
Comment对象的内部引用会自动指向新的注释内容; - 即便存在同范围多条注释的特殊场景,
Comments[索引]的引用也是动态的,集合新增元素后,原索引对应的对象会随集合变化更新,无法保持初始指向的实例。
规避方法
不要直接保存Comment对象的引用,而是保存注释的唯一标识Comment.ID(Word为每条注释分配的不变唯一ID),每次需要访问时通过ID精准查找:
// 类级别变量,保存注释ID而非对象引用 private int? _commentId; private void Application_DocumentBeforeSave(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel) { if(_commentId.HasValue) { // 通过ID定位目标注释 var targetComment = Doc.Comments.Cast<Word.Comment>() .FirstOrDefault(c => c.ID == _commentId.Value); if(targetComment != null) { MessageBox.Show(targetComment.Range.Text); } } else { var comments = Doc.Range().Comments; if (comments.Count > 0) { // 保存第一条注释的ID _commentId = comments[1].ID; } } }
内容的提问来源于stack exchange,提问作者Peter Dongan
相关产品推荐
相关产品推荐

