1. 程式人生 > >AutoCAD .Net 使用擴充套件字典儲存自定義資料

AutoCAD .Net 使用擴充套件字典儲存自定義資料

每個 AutoCAD 資料庫元素物件(DBObject)都可以使用擴充套件字典來儲存自定義資料。
通常這一機制用來為圖元物件(比如:線、圓等)儲存非圖形資料。
以下示例程式碼實現:
AddXRecordToEntity: 讓使用者選擇一圖元,然後在圖元的擴充套件字典中儲存自定義資料。
GetXRecordFromEntity: 讓使用者選擇一圖元,讀取圖元的擴充套件字典中儲存的自定義資料。

[CommandMethod("AddXRecordToEntity")]
public void AddXRecordToEntity()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    Database db = doc.Database;

    PromptEntityResult per = doc.Editor.GetEntity("\nSelect an entity: "
); if (per.Status != PromptStatus.OK) { return; } using (Transaction tr = db.TransactionManager.StartTransaction()) { Entity entity = tr.GetObject(per.ObjectId, OpenMode.ForWrite) as Entity; if (entity.ExtensionDictionary == ObjectId.Null) { entity.CreateExtensionDictionary(); } DBDictionary xDict = tr.GetObject(entity.ExtensionDictionary, OpenMode.ForRead) as
DBDictionary; if (!xDict.Contains("CAXDEV")) { xDict.UpgradeOpen(); Xrecord xRec = new Xrecord(); ResultBuffer rb = new ResultBuffer(); rb.Add(new TypedValue((int)DxfCode.Text, "Hello www.caxdev.com")); rb.Add(new TypedValue((int
)DxfCode.Int32, 123)); rb.Add(new TypedValue((int)DxfCode.Real, 1.2345)); xRec.Data = rb; xDict.SetAt("CAXDEV", xRec); tr.AddNewlyCreatedDBObject(xRec, true); } tr.Commit(); } } [CommandMethod("GetXRecordFromEntity")] public void GetXRecordFromEntity() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; PromptEntityResult per = doc.Editor.GetEntity("\nSelect an entity: "); if (per.Status != PromptStatus.OK) { return; } using (Transaction tr = db.TransactionManager.StartTransaction()) { Entity entity = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Entity; if (entity.ExtensionDictionary != ObjectId.Null) { DBDictionary xDict = tr.GetObject(entity.ExtensionDictionary, OpenMode.ForRead) as DBDictionary; if (xDict.Contains("CAXDEV")) { ObjectId xRecId = xDict.GetAt("CAXDEV"); Xrecord xRec = tr.GetObject(xRecId, OpenMode.ForRead) as Xrecord; if (xRec == null) return; foreach (TypedValue tv in xRec.Data) { doc.Editor.WriteMessage("\nTypeCode: {0}; Value: {1}", tv.TypeCode, tv.Value); } } } } }

參考文章: