AutoCAD Civil 3D Help: Using Collections Within the Document Object

在Document对象中使用集合


Document 对象不仅包括了AutoCAD Civil 3D 图形元素(如 点Point路线Alignment) ,而且也包含了修饰这些元素的对象(如样式和标签样式)。Civil Document中大多数对象的集合是ObjectID集合 (Autodesk.AutoCAD.DatabaseServices.ObjectIdCollection) 。在使用之前,这些集合中的对象必须通过Transaction.GetObject()方法取得,并转换(cast)为相应的类型。

注:

在COM API中, document 对象包含在对象的集合中,不需要cast转换。

ObjectId Collection 对象实现了IList 接口,可以进行枚举或者通过下标来访问。下面是一个通过foreach遍历Corridor集合的例子,取得结果ObjectId并转换为一个Corridor以访问其方法和属性:

public static void iterateCorridors () {
    CivilDocument doc = CivilApplication.ActiveDocument;
    using ( Transaction ts = Application.DocumentManager.MdiActiveDocument.
            Database.TransactionManager.StartTransaction() ) {
        foreach ( ObjectId objId in doc.CorridorCollection ) {
            Corridor oCorridor = ts.GetObject(objId, OpenMode.ForRead) as Corridor;
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Corridor: {0}\nLargest possible triangle side: {1}\n",
                oCorridor.Name, oCorridor.MaximumTriangleSideLength);
        }
    }
}

请参照Civil 3D .NET API手册获取 ObjectId 集合(Collections—)的更多信息。

下面的例子创建了一个新的点样式:

ObjectId pointStyleID = doc.Styles.PointStyles.Add("Name");
// Now a new point style is added to the collection of styles,
// and we can modify it by setting the properties
// of the oPointStyle object, which we get from the Transaction ts:
PointStyle oPointStyle = ts.GetObject(pointStyleID, OpenMode.ForWrite) as PointStyle;
oPointStyle.Elevation = 114.6;
// You must commit the transaction for the add / modify operation
// to take effect
ts.Commit();

如果你尝试添加一个和既存元素属性相同的新元素,或者试着访问一个不存在的对象,抑或移除一个不存在/使用中的对象,那么将会导致一个异常,你应该捕获这个异常并采取相应措施。

下面的例子演示了一种处理异常的做法:

// 尝试访问一个叫做“Name”的样式
try {
    // 如果访问对象不存在,会引发一个ArgumentException异常 
    ObjectId pointStyleId = doc.Styles.PointStyles["Name"];
    // 对该样式的操作...
} catch ( ArgumentException e ) {
    ed.WriteMessage(e.Message);
}

父主题:

Root 对象

results matching ""

    No results matching ""