0

我创建了一个自定义类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System.Threading;
using Autodesk.AutoCAD.Customization;

namespace Plugin
{
    public class Bar : BlockTableRecord
    {
        /// <summary>
        /// Bar is a set of lines together with a text represenging a single object
        /// It has default length, width and its described by a label at the top of the Bar.
        /// </summary>

        //Autocad document
        private Document doc;
        private DocumentLock lockedDoc;
        private Editor editor;
        private Database db;

        //id
        private static int count;

        ///getters and setters for Bar properties
        public int Position { set; get; }
        public double Length { set; get; }
        public double Width { set; get; }
        public LineWeight Weight { set; get; }
        public int ColorIndex { set; get; }
        private int Bars { set; get; }
        private double BarLength { set; get; }
        private double Angle { set; get; }

        //drawing objects
        public DBText Title;
        public DBText LengthText;
        public Polyline line;

        //helper variables

        public void Instantiate()
        {
            Interlocked.Increment(ref count);

            //default values
            Weight = LineWeight.LineWeight030;
            Width = 30;
            ColorIndex = 4;
            BarLength = 250;
            Position = count;

            Title = new DBText();
            Title.ColorIndex = 2;
            Title.Height = 16;

            LengthText = new DBText();
            LengthText.Height = 8;

            Name = "Bar" + count;
        }

        public Bar()
        {
            Instantiate();
        }

        public Bar(Document d)
        {
            doc = d;
            editor = doc.Editor;
            db = doc.Database;

            Instantiate();
        }

        ~Bar()
        {
            Interlocked.Decrement(ref count);
        }

        public void drawLineFromUserInput()
        {
            using (lockedDoc = doc.LockDocument())
            {
                PromptPointResult pointResult;
                PromptPointOptions pointOptions = new PromptPointOptions("");

                pointOptions.Message = "\nEnter the start point of the line: ";
                pointResult = editor.GetPoint(pointOptions);
                Point3d startLinePoint = pointResult.Value;

                if (pointResult.Status == PromptStatus.Cancel)
                {
                    Application.ShowAlertDialog("Error getting the point");
                    return;
                }

                pointOptions.Message = "\nEnter the end point of the line: ";
                pointOptions.UseBasePoint = true;
                pointOptions.BasePoint = startLinePoint;
                pointResult = editor.GetPoint(pointOptions);
                Point3d endLinePoint = pointResult.Value;

                if (pointResult.Status == PromptStatus.Cancel)
                {
                    Application.ShowAlertDialog("Error getting the point");
                    return;
                }

                try
                {
                    using (Transaction transaction = db.TransactionManager.StartTransaction())
                    {
                        db.LineWeightDisplay = true;

                        BlockTable blockTable;
                        BlockTableRecord blockTableRecord;

                        blockTable = transaction.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        blockTableRecord = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                        Polyline drawnLine = new Polyline();//startLinePoint, endLinePoint
                        drawnLine.AddVertexAt(0, new Point2d(startLinePoint.X, startLinePoint.Y), 0, 0, 0);
                        drawnLine.AddVertexAt(1, new Point2d(endLinePoint.X, endLinePoint.Y), 0, 0, 0);
                        drawnLine.SetDatabaseDefaults();
                        drawnLine.LineWeight = Weight;
                        drawnLine.ColorIndex = ColorIndex;

                        blockTableRecord.AppendEntity(drawnLine);
                        transaction.AddNewlyCreatedDBObject(drawnLine, true);

                        editor.Regen();

                        line = drawnLine.Clone() as Polyline;

                        PromptSelectionResult selectionResult = editor.SelectLast();

                        if (selectionResult.Status == PromptStatus.OK)
                        {
                            PromptPointResult ppr = editor.Drag(selectionResult.Value, "Select the location of the Bar",
                                delegate(Point3d pt, ref Matrix3d mat)
                                {
                                    if (startLinePoint == pt)
                                    {
                                        return SamplerStatus.NoChange;
                                    }
                                    else
                                    {
                                        mat = Matrix3d.Displacement(startLinePoint.GetVectorTo(pt));
                                    }
                                    return SamplerStatus.OK;
                                });

                            if (ppr.Status == PromptStatus.OK)
                            {
                                Point3d newLocation = ppr.Value;
                                Matrix3d mat = Matrix3d.Displacement(startLinePoint.GetVectorTo(newLocation));

                                line.TransformBy(mat);

                                Length = line.Length;

                                Angle = PointUtil.angleFromXAxis(line.StartPoint, line.EndPoint);

                                Bars = (int)Math.Ceiling(Length / BarLength);

                                Title.TextString = "Pos " + Position + " ϕ " + Width + "mm tot(" + count + ")";

                                LengthText.TextString = Math.Round(Length).ToString();

                                DBText info = new DBText();
                                info.Visible = false;
                                info.TextString = "Position=" + Position;

                                Point3d startPoint = line.StartPoint;

                                line.TransformBy(Matrix3d.Displacement(line.StartPoint.GetVectorTo(Point3d.Origin)));

                                Title.TransformBy(Matrix3d.Rotation(Angle, Vector3d.ZAxis, Point3d.Origin));

                                LengthText.TransformBy(Matrix3d.Rotation(Angle, Vector3d.ZAxis, Point3d.Origin));

                                Title.TransformBy(Matrix3d.Displacement(getMoveTextVector(line.StartPoint, line.EndPoint, Math.PI / 16, 0.1 * Length)));

                                LengthText.TransformBy(Matrix3d.Displacement(getMoveTextVector(line.StartPoint, line.EndPoint, -Math.PI / 48, 0.1 * Length)));

                                Title.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(line.StartPoint)));

                                blockTable.UpgradeOpen();
                                blockTable.Add(this);
                                transaction.AddNewlyCreatedDBObject(this, true);

                                AppendEntity(Title);
                                transaction.AddNewlyCreatedDBObject(Title, true);

                                AppendEntity(LengthText);
                                transaction.AddNewlyCreatedDBObject(LengthText, true);

                                AppendEntity(line);
                                transaction.AddNewlyCreatedDBObject(line, true);

                                AppendEntity(info);
                                transaction.AddNewlyCreatedDBObject(info, true);

                                BlockReference blockReference = new BlockReference(Point3d.Origin, this.ObjectId);
                                blockReference.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(startPoint)));

                                blockTableRecord.AppendEntity(blockReference);
                                transaction.AddNewlyCreatedDBObject(blockReference, true);

                            }
                        }

                        transaction.Commit();
                    }
                }
                catch (System.Exception e)
                {
                    Application.ShowAlertDialog(e.Message);
                }
            }
        }

        public static Vector3d getMoveTextVector(Point3d startPoint, Point3d endPoint, double angle, double width)
        {
            Line l = new Line(startPoint, endPoint);

            Point3d p = l.GetPointAtDist(l.Length / 2 - width);

            Vector3d vector = l.StartPoint.GetVectorTo(p);

            vector = vector.RotateBy(angle, Vector3d.ZAxis);

            return vector;
        }

        public void UpdatePosition(int position)
        {
            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                Position = position;
                Title.TextString = "Pos " + Position + " ϕ " + Width + "mm tot(" + count + ")";
                transaction.Commit();
            }
        }


    }
}

我已将 Bar 的实例添加到 BlockTable。当我遍历所有 BlockTableRecords 时:

    [CommandMethod("Edit")]
    public static void EditEntity()
    {
        PromptEntityResult per = editor.GetEntity("Select Entity");

        if (per.Status == PromptStatus.OK)
        {
            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                BlockReference blockReference = transaction.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference;

                if (blockReference != null)
                {
                    BlockTableRecord btr = blockReference.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord;

                    new PositionProperties(doc, btr).Show();
                }
            }
        }
    }

我获得了 BlockTableRecord 的实例,但我无法获得我创建的 Bar 类的实例。有没有办法存储我创建的类的信息?

4

2 回答 2

1

查看我的 GitHub。

https://github.com/XxZer0xX

这是一个简单的例子。

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

namespace stackclass
{
/// <summary>
/// Description of MyClass.
/// </summary>
public class MyClass : BlockTableRecord
{
    public string BlkRecordName {get;set;}

    public MyClass(BlockTableRecord _RecordParam)
    {
        BlkRecordName = _RecordParam.Name;
    }

    public MyClass(){}
}


public static class MyClassInstanciator 
{
    public static void Main(string[] args) 
    {
        var AcDoc = Application.DocumentManager.MdiActiveDocument;
        using (var Trans = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction()) {

            var BlkTable = Trans.GetObject(AcDoc.Database.BlockTableId,OpenMode.ForRead) as BlockTable;
            foreach (var BlkRcrdId in BlkTable) {
                var _blkRcrd = Trans.GetObject(BlkRcrdId,OpenMode.ForRead) as BlockTableRecord;
                var MyClassRcd = new MyClass(_blkRcrd);
                // or
                var _MyClassRcd = new MyClass();
                _MyClassRcd.BlkRecordName = _blkRcrd.Name;
            }
        }
    }
}

更新:

根据您构建类的方式,您要么必须实例化类的新版本,然后分配 ,Id = 2;要么必须添加静态类修饰符,然后具有名为Id.

例子:

public static class MyClass : BlockTableRecord
{
    public static string Id {get;set;}
}

public static class UsingStaticClass 
{
    public static void setIdWithValue(string[] args) 
    {
             MyClass.Id = 2;
    }

    public static void RetrieveIdValue()
    {
           var someOtherValue = MyClass.Id;
    }
}

你是这个意思吗?

附加更新:

您在这里的代码使用不正确。

foreach (ObjectId obj in bt)
{
    BlockTableRecord btr = obj.GetObject(OpenMode.ForRead) as BlockTableRecord;
}

在 AutoCad.Database 变量内部的 foreach 中是一个 objectId,obj就像在循环中一样。

在上面的示例中,您尝试使用 BlockTableRecord 的属性来获取对象。您的代码应该是这样的,并且应该在事务中

foreach(ObjectId ObjId in BlkTbl)
{
     var BlkRcd = Transaction.GetObject(ObjId,OpenMode.ForRead) as BlockTableRecord;
}

您需要使用事务从数据库中获取任何对象。

于 2013-07-23T22:12:45.107 回答
0

如果我需要使用对象存储信息,我使用 Xdata。几乎每个对象都有自己的 XDATA 容器。它几乎像字典一样工作。你可以在网上找到足够多的例子。或者,您可以检查 XRecords 以获取大量数据或二进制数据...这种方式并不真正支持自定义对象。要创建自己的对象类型,您需要切换到 ObjectARX....

HTH,丹尼尔

于 2015-03-23T08:46:56.667 回答