我有一個抽象類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;
}
}
請發表[MCVE。這麼少的信息很難提供幫助。 –
真的沒有更多的信息是必要的..但好的,給我一個秒 –
「WebTile」的構造函數將this.html'設置爲它的當前值(它是null)。將其更改爲'this.html = html;'。另外,如果你想檢查'tile'的類型,可以使用if(tile是WebTile)'或者使用'as' cast來代替類型名稱的切換。 – Lee