CAD二次开发中DoubleCollection用法详解
在 AutoCAD .NET API 中DoubleCollection是一个用于存储双精度浮点数集合的类常用于定义多段线Polyline的顶点坐标或样条曲线的拟合点等。核心用法DoubleCollection通常作为参数传递给需要一系列连续数值的构造函数或方法。其核心用法是按顺序存储坐标值例如(x1, y1, z1, x2, y2, z2, ...)。1. 创建与填充 DoubleCollection你可以通过多种方式创建并填充一个DoubleCollection对象。// 方法一使用构造函数并逐个添加 DoubleCollection vertices1 new DoubleCollection(); vertices1.Add(0.0); // X1 vertices1.Add(0.0); // Y1 vertices1.Add(0.0); // Z1 vertices1.Add(100.0); // X2 vertices1.Add(100.0); // Y2 vertices1.Add(0.0); // Z2 // 方法二使用集合初始化器更简洁 DoubleCollection vertices2 new DoubleCollection { 0.0, 0.0, 0.0, // 顶点1 (X, Y, Z) 100.0, 0.0, 0.0, // 顶点2 100.0, 100.0, 0.0, // 顶点3 0.0, 100.0, 0.0 // 顶点4 };2. 典型应用创建三维多段线 (Polyline3d)这是DoubleCollection最经典的应用场景之一用于传递多段线所有顶点的三维坐标。using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; public class DoubleCollectionExample { [CommandMethod(CreatePoly3d)] public void CreatePoly3d() { Document doc Application.DocumentManager.MdiActiveDocument; Database db doc.Database; using (Transaction tr db.TransactionManager.StartTransaction()) { // 打开块表记录模型空间以写入实体 BlockTable bt (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); // 1. 定义多段线的顶点坐标集合 DoubleCollection vertices new DoubleCollection { // 顶点1 0, 0, 0, // 顶点2 200, 0, 50, // 顶点3200, 150, 100, // 顶点4 0, 150, 0 }; // 2. 创建三维多段线对象 Polyline3d poly3d new Polyline3d(Poly3dType.SimplePoly, vertices, false); // 3. 将实体添加到模型空间并提交事务 btr.AppendEntity(poly3d); tr.AddNewlyCreatedDBObject(poly3d, true); tr.Commit(); } } }3. 与其他几何类型的转换有时需要将Point3dCollection等更结构化的数据转换为DoubleCollection。// 假设有一个 Point3dCollectionPoint3dCollection points new Point3dCollection { new Point3d(10, 20, 0), new Point3d(50, 60, 10), new Point3d(100, 30, 20) }; // 转换为 DoubleCollection DoubleCollection coordCollection new DoubleCollection(); foreach (Point3d pt in points) { coordCollection.Add(pt.X); coordCollection.Add(pt.Y); coordCollection.Add(pt.Z); } // 此时 coordCollection 包含:10, 20, 0, 50, 60, 10, 100, 30, 20关键注意事项事项说明数据顺序必须严格按照X, Y, Z, X, Y, Z...的顺序添加坐标值否则图形会错乱。元素数量DoubleCollection中元素的总数必须是 3 的倍数对于三维坐标因为每个顶点由三个double值 (X, Y, Z) 构成。性能考量对于大量顶点建议在创建集合时预估大小或使用更高效的填充方式如数组转换以减少内存重新分配。应用场景主要用于Polyline3d、某些Spline拟合数据的构造以及需要传递原始双精度数组的低层级 API。总结DoubleCollection在 AutoCAD 二次开发中是一个基础的、用于顺序存储双精度数值的数据容器尤其在构造基于顶点序列的图形对象如三维多段线时不可或缺。使用时需严格保证坐标数据的顺序和数量正确。参考来源AutoCAD二次开发基础