2016-02-05 52 views
-1

我有一個抽象類Tile。 我有另一個類WebTile繼承Tile類。 WebTile有一個private string html,Tile沒有。C#顯式強制轉換派生類並獲取特定變量

public abstract class Tile 
{ 
    private string name; 
    private string description; 

    public string Name 
    { 
     get { return name; } 
    } 

    public string Description 
    { 
     get { return description; } 
    } 

    protected Tile(string name, string description) 
    { 
     this.name = name; 
     this.description = description; 
    } 
} 

public class WebTile : Tile 
    { 
     private string html; 
     public string HTML 
     { 
      get { return html; } 
     } 
     public WebTile(string name, string description, string html) : base(name, description) 
     { 
      this.html = HTML; 
     } 
    } 

我有(List<Tile>)

我遍歷列表返回瓷磚的列表的方法,並鑄鉛字WebTile的瓷磚到WebTile。

然後我想要的html字符串。但演員陣容後它變得空虛了!我錯過了什麼?

foreach (Tile tile in xmlparser.GetTiles()) 
      { 
       switch (tile.GetType().ToString()) 
       { 
        case "Dashboard.Tiles.WebTile": 
         WebTile _tile = tile as WebTile; 
         sb.Append("<div class=\"panel panel-default\">"); 
         sb.Append("<div class=\"panel-heading\">" + _tile.Name + "</div>"); 
         sb.Append("<div class=\"panel-body\">"); 
         sb.Append(_tile.HTML); // <--- THIS IS EMPTY!! 
         sb.Append("</div>").Append("</div>"); 
         break; 
        default: 
         break; 
       } 
      } 
+0

請發表[MCVE。這麼少的信息很難提供幫助。 –

+0

真的沒有更多的信息是必要的..但​​好的,給我一個秒 –

+2

「WebTile」的構造函數將this.html'設置爲它的當前值(它是null)。將其更改爲'this.html = html;'。另外,如果你想檢查'tile'的類型,可以使用if(tile是WebTile)'或者使用'as' cast來代替類型名稱的切換。 – Lee

回答

1
public class WebTile : Tile 
    { 
     private string html; 
     public string HTML 
     { 
      get { return html; } 
     } 
     public WebTile(string name, string description, string html) : base(name, description) 
     { 
     //wronge 
     // this.html = HTML; 
     //correct 
     this.html = html; 
     } 
    } 
2

可以使用代替對完全限定的類型名稱的轉換的LINQ的OfType方法:

foreach (WebTile tile in xmlparser.GetTiles().OfType<WebTile>()) 
{ 
    sb.Append("<div class=\"panel panel-default\">"); 
    sb.Append("<div class=\"panel-heading\">" + tile.Name + "</div>"); 
    sb.Append("<div class=\"panel-body\">"); 
    sb.Append(tile.HTML); 
    sb.Append("</div>").Append("</div>"); 
} 

但你的構造函數是錯誤的 - 你是從屬性assinging私人領域,而不是即在傳遞的參數:

public WebTile(string name, string description, string html) : base(name, description) 
{ 
    this.html = html; // not HTML 
}