在C#中将父类强制转换为子类

本文关键字:转换 子类 父类 | 更新日期: 2023-09-27 18:28:39

我正在使用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对象(子类)。

对于这个问题,有没有简单的解决方法?

在C#中将父类强制转换为子类

您需要为OpeningDataTable创建一个以Table为参数的构造函数。

不能将Table强制转换为OpeningDataTable的原因是Table不是OpeningDataTable,就像object不是int一样。

不能向下转换对类似对象的引用,除非它确实是对子类对象的引用。例如,以下内容很好。。。

string foo = "Yup!";
object fooToo = foo;
string fooey = fooToo as string;
Console.WriteLine(fooey);  // prints Yup!

因为CCD_ 13只是将CCD_ 14引用为CCD_。

考虑使用Decorator设计模式,并向OpeningDataTable添加一个接受Table arg:的构造函数

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>
}