AutoCAD .NET获取选中块属性:初始方法返回Null的原因排查
问题原因分析
你代码里返回Null的核心原因是类型不匹配:
- 你通过
GetSelection()获取到的是绘图区中放置的块参照(BlockReference),这是块的实例对象; - 而你试图把它强制转换成块表记录(BlockTableRecord),这是块的定义对象(存储在BlockTable里,用于定义块的结构、属性模板等)。
两者是完全不同的AutoCAD对象类型,所以用块参照的ObjectId去调用GetObject()并转成BlockTableRecord,自然会返回Null。
修正思路
如果要获取块定义的BlockTableRecord,需要先从选中的BlockReference里拿到它对应的块定义ID,再用这个ID打开BlockTableRecord:
public void getattrib() { Database acCurDb = Application.DocumentManager.MdiActiveDocument.Database; Document acDoc = Application.DocumentManager.MdiActiveDocument; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(); if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; ObjectId blkRefId = acSSet[0].ObjectId; // 先打开选中的块参照 BlockReference blkRef = acTrans.GetObject(blkRefId, OpenMode.ForRead) as BlockReference; if (blkRef != null) { // 从块参照中获取块定义的ID ObjectId blkDefId = blkRef.BlockTableRecord; // 再打开对应的块表记录 BlockTableRecord br = acTrans.GetObject(blkDefId, OpenMode.ForRead) as BlockTableRecord; // 此时br就不会是Null了 } } acTrans.Commit(); } }
另外,如果你最终目的是读取块参照的关联属性值,其实不需要打开BlockTableRecord,直接遍历BlockReference的属性集合即可:
if (blkRef != null && blkRef.HasAttributes) { foreach (ObjectId attribId in blkRef.AttributeCollection) { AttributeReference attrib = acTrans.GetObject(attribId, OpenMode.ForRead) as AttributeReference; if (attrib != null) { // 获取属性标签和值 string tag = attrib.Tag; string value = attrib.TextString; // 这里可以处理属性内容,比如输出到命令行 acDoc.Editor.WriteMessage($"\n属性标签: {tag}, 属性值: {value}"); } } }
内容的提问来源于stack exchange,提问作者farhan chowdhry
相关产品推荐
相关产品推荐

