最终,您需要重新审视 AutoCAD 对象模型。BlockTableRecord“模型空间”将包含所有*具有图层分配的 AutoCAD 实体。打开 BlockTableRecord 以供读取后,您可以过滤到与您感兴趣的任何层匹配的实体。LINQ 可以在这里派上用场。
在这种情况下,您实际上并不关心图层的 objectID,只关心名称。只有在想要更改图层时才真正打开 LayerTableRecord。如果您要更改实体属性,您确实需要熟悉 Transaction 类。通过利用 RXObject.GetClass() 在 AutoCAD 中使用“As”还有一个更快的替代方法。
*实体也可以存在于其他 BlockTableRecords 中(例如任何其他布局),但现在您可能只使用模型空间就可以了。
这里有一个小片段可以帮助您入门:
var acDoc = Application.DocumentManager.MdiActiveDocument;
var acDb = acDoc.Database;
using (var tr = database.TransactionManager.StartTransaction())
{
try
{
var entClass = RXObject.GetClass(typeof(Entity));
var modelSpaceId = SymbolUtilityServices.GetBlockModelSpaceId(acDb);
var modelSpace = (BlockTableRecord)tr.GetObject(modelSpaceId, OpenMode.ForRead);
foreach (ObjectId id in modelSpace)
{
if (!id.ObjectClass.IsDerivedFrom(entClass)) // For entity this is a little redundant, but it works well with derived classes
continue;
var ent = (Entity)tr.GetObject(id, OpenMode.ForRead)
// Check for the entity's layer
// You'll need to upgrade the entity to OpenMode.ForWrite if you want to change anything
}
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
acDoc.Editor.WriteMessage(ex.Message);
}
}