向集合对象中添加新的成员
 
 

要向集合中添加新的成员,请使用 Add 方法。例如,以下代码创建一个新图层,并将其添加到层表中:

VB.NET

Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
 
<CommandMethod("AddMyLayer")> _
Public Sub AddMyLayer()
  ''获得当前文档和数据库,并启动一个事务   Get the current document and database, and start a transaction
  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument
  Dim acCurDb As Database = acDoc.Database
 
  Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()
      ''返回当前数据库的层表   Returns the layer table for the current database
      Dim acLyrTbl As LayerTable
      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _
                                   OpenMode.ForRead)
 
      ''检验名字为 MyLayer 的图层是否已经存在在层表中 Check to see if MyLayer exists in the Layer table
      If Not acLyrTbl.Has("MyLayer") Then
          '' 以写的方式打开层表 Open the Layer Table for write
          acLyrTbl.UpgradeOpen()
 
          '' 创建一个新的层表记录并命名为“MyLayer”  Create a new layer table record and name the layer "MyLayer"
          Dim acLyrTblRec As LayerTableRecord = New LayerTableRecord
          acLyrTblRec.Name = "MyLayer"
 
          '' 添加新的层表记录到层表和事务中 Add the new layer table record to the layer table and the transaction
          acLyrTbl.Add(acLyrTblRec)
          acTrans.AddNewlyCreatedDBObject(acLyrTblRec, True)
 
          '' 确认所做的修改  Commit the changes
          acTrans.Commit()
      End If
 
      '' 销毁事务  Dispose of the transaction
  End Using
End Sub

C#

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
 
[CommandMethod("AddMyLayer")]
public static void AddMyLayer()
{
  // Get the current document and database, and start a transaction
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;
 
  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Returns the layer table for the current database
      LayerTable acLyrTbl;
      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                   OpenMode.ForRead) as LayerTable;
 
      // Check to see if MyLayer exists in the Layer table
      if (acLyrTbl.Has("MyLayer") != true)
      {
          // Open the Layer Table for write
          acLyrTbl.UpgradeOpen();
 
          // Create a new layer table record and name the layer "MyLayer"
          LayerTableRecord acLyrTblRec = new LayerTableRecord();
          acLyrTblRec.Name = "MyLayer";
 
          // Add the new layer table record to the layer table and the transaction
          acLyrTbl.Add(acLyrTblRec);
          acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
 
          // Commit the changes
          acTrans.Commit();
      }
 
      // Dispose of the transaction
  }
}
VBA/ActiveX 代码参考