请求修复AutoCAD Plant 3D对象属性获取代码:仅筛选Plant 3D对象
修复AutoCAD Plant 3D属性获取代码:过滤普通CAD对象
你的代码报错原因是:当选中普通AutoCAD对象(直线、块、文字等)时,DataLinksManager.FindAcPpRowId无法找到对应的Plant 3D数据行,返回无效ID后调用GetAllProperties会触发异常。
以下是修复后的代码,核心是先过滤非Plant 3D对象,同时增加异常处理提升健壮性:
public void GetPipingProperties() { Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor; PromptSelectionOptions opts = new PromptSelectionOptions(); opts.MessageForAdding = "Select objects to obtain properties: "; PromptSelectionResult selRes = ed.GetSelection(opts); if (selRes.Status == PromptStatus.OK) { PlantProject currentProj = PlantApplication.CurrentProject; PipingProject pipingProj = (PipingProject)currentProj.ProjectParts["Piping"]; DataLinksManager dlm = pipingProj.DataLinksManager; foreach (ObjectId objectId in selRes.Value.GetObjectIds()) { // 直接过滤非Plant 3D对象 if (!PlantObject.IsPlantObject(objectId)) { ed.WriteMessage($"\n跳过非Plant 3D对象: {objectId}"); continue; } try { int rowId = dlm.FindAcPpRowId(objectId); // 额外校验rowId有效性,避免极端情况 if (rowId == -1) { ed.WriteMessage($"\n未找到对象{objectId}对应的Plant 3D数据"); continue; } List<KeyValuePair<string, string>> properties = dlm.GetAllProperties(rowId, true); ed.WriteMessage($"\n对象{objectId}的属性:"); foreach (var prop in properties) { ed.WriteMessage($"\n属性名: {prop.Key} = {prop.Value}"); } } catch (Exception ex) { ed.WriteMessage($"\n处理对象{objectId}时出错: {ex.Message}"); } } } else { ed.WriteMessage("\n选择已取消或发生错误。"); } }
关键修改说明
- 过滤非Plant对象:使用
PlantObject.IsPlantObject(objectId)快速判断,直接跳过普通CAD对象,这是最简便且可靠的方式。 - 异常捕获:加入
try-catch块,避免单个对象处理失败导致整个程序中断。 - rowId有效性校验:即使是Plant对象,也可能存在无对应数据行的情况,额外判断rowId是否为-1可以避免无效调用。
- 代码优化:用
foreach遍历属性集合,比原代码的for循环更简洁易读。
内容的提问来源于stack exchange,提问作者Traiduong014969
相关产品推荐
相关产品推荐

