2

我正在使用 C# 和 .NET Framework 为 AutoCAD 2014 编写插件。我像这样扩展了 Autodesk 的Table课程:

public class OpeningDataTable : Autodesk.AutoCAD.DatabaseServices.Table

我的想法是,我想将已经在 AutoCAD 绘图上绘制的表格作为一个实例从绘图中拉出,OpeningDataTable这样我就可以使用我编写的方法来操作数据。我这样做是这样的:

OpeningDataTable myTable = checkForExistingTable(true);

public Autodesk.AutoCAD.DatabaseServices.Table checkForExistingTable(bool isWindow)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; //Current drawing
            Transaction tr = doc.TransactionManager.StartTransaction();
            DocumentLock docLock = doc.LockDocument();
            TypedValue[] tableItem = new TypedValue[] { new TypedValue(0, "ACAD_TABLE") };
            SelectionFilter tableSelecFilter = new SelectionFilter(tableItem);
            Editor ed = doc.Editor; //Editor object to ask user where table goes, subclass of Document

            using (tr)
            {
                PromptSelectionResult selectResult = ed.SelectAll(tableSelecFilter);
                if (selectResult.Status == PromptStatus.OK)
                {
                    SelectionSet tableSelSet = selectResult.Value;
                    for (int i = 0; i < tableSelSet.Count; i++)
                    {
                        Autodesk.AutoCAD.DatabaseServices.Table tableToCheck = (Autodesk.AutoCAD.DatabaseServices.Table)tr.GetObject(tableSelSet[i].ObjectId, OpenMode.ForRead);
                        String tableTitle = tableToCheck.Cells[0, 0].Value.ToString();
                        if(tableTitle.Equals("Window Schedule") && isWindow == true)
                            return (OpeningDataTable)tableToCheck;
                        if (tableTitle.Equals("Door Schedule") && isWindow == false)
                            return (OpeningDataTable)tableToCheck;
                    }
                }
                return null;
            }
        }

但是,我收到一条错误消息,提示我无法将Table对象(父类)转换为OpeningDataTable对象(子类)。

这个问题有简单的解决方法吗?

4

2 回答 2

2

OpeningDataTable您将需要为其Table作为参数创建一个构造函数。

您不能将 aTable转换为 an的原因OpeningDataTable是 aTable不是 anOpeningDataTable就像 an objectis not an一样int

于 2014-11-01T20:38:09.267 回答
2

您不能像这样向下转换对对象的引用,除非它确实是对子类对象的引用。例如,以下是好的......

string foo = "Yup!";
object fooToo = foo;
string fooey = fooToo as string;

Console.WriteLine(fooey);  // prints Yup!

...因为fooToo只是简单地将 a 引用StringObject: 所以沮丧的作品。

考虑使用装饰器设计模式并添加一个OpeningDataTable接受Tablearg 的构造函数:

public class OpeningDataTable : Autodesk.AutoCAD.DatabaseServices.Table
{
    private Table _table; // the decorated Table

    public OpeningDataTable(Table table)
    {
        _table = table;
    }

    // <your methods for working with the decorated Table>
}
于 2014-11-01T20:42:08.610 回答