2014-11-01 27 views
2

我正在使用C#和.NET Framework爲AutoCAD 2014編寫一個插件。我擴展Autodesk的Table類,像這樣:將父類投射到C#中的子類中#

public class OpeningDataTable : Autodesk.AutoCAD.DatabaseServices.Table 

的想法是,我想拉已經繪製在AutoCAD繪圖出來的圖紙爲OpeningDataTable實例的表,所以我可以操縱與方法,數據I」已經寫了。我這樣做,就像這樣:

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對象(子類)。

這個問題有一個簡單的解決方法嗎?

+1

號你可以不投了'''到除非B'的了''實際類型是'乙'或者繼承'B'的東西。在這裏,變量的實際類型是'Table',並且您試圖將其轉換爲'OpeningDataTable',其中'Table'不會繼承'OpeningDataTable'。 – MarcinJuraszek 2014-11-01 20:37:11

回答

2

您將需要爲OpeningDataTable創建一個構造函數,它將Table作爲參數。

,你不能施放TableOpeningDataTable的原因是Table不是OpeningDataTable就像一個object不是一個int

+0

好,簡單的解釋。 – J0e3gan 2014-11-01 20:53:57

2

不能向下引用這樣的對象,除非它真的是對子類的對象的引用。例如,下面是細...

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

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

...因爲fooToo僅僅是引用StringObject:這麼喪氣的作品。

考慮使用Decorator design pattern並添加構造函數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> 
}