コレクション オブジェクトのメンバーを削除する(.NET)

メンバー オブジェクトの Erase メソッドを使用して、コレクション オブジェクトのメンバーを削除できます。たとえば、次のコードは LayerTable オブジェクトから画層 MyLayer を削除します。

図面から画層を削除する前に、安全に削除できることを確認する必要があります。画層またはブロックや文字スタイルなどの他の名前付きオブジェクトを削除できるかどうかを判定するには、Purge メソッドを使用します。

C# の例

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
 
[CommandMethod("RemoveMyLayer")]
public static void RemoveMyLayer()
{
  // 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)
      {
          LayerTableRecord acLyrTblRec;
          acLyrTblRec = acTrans.GetObject(acLyrTbl["MyLayer"],
                                          OpenMode.ForWrite) as LayerTableRecord;
 
          try
          {
              acLyrTblRec.Erase();
              acDoc.Editor.WriteMessage("\n'MyLayer' was erased");
 
              // Commit the changes
              acTrans.Commit();
          }
          catch
          {
              acDoc.Editor.WriteMessage("\n'MyLayer' could not be erased");
          }
      }
      else
      {
          acDoc.Editor.WriteMessage("\n'MyLayer' does not exist");
      }
 
      // Dispose of the transaction
  }
}

オブジェクトを削除した後は、それ以降にプログラムでそのオブジェクトに再びアクセスしないようにする必要があります。アクセスすると、エラーが発生します。前のサンプルでは、オブジェクトに再びアクセスする前に、オブジェクトが存在するかどうかをテストしています。オブジェクトの削除を要求するときは、Has メソッドを使用してオブジェクトが存在するかどうかを確認するか、Try ステートメントを使用して発生した例外を検出する必要があります。