我在這裏有一個面向對象的問題。我有兩個具有共同屬性和特定屬性的會話。我創建了一個基類並封裝了所有常用屬性/方法。 兩個會話有一個名爲Ranges的公共類型,它們又具有公共屬性和會話的特定屬性。因此,我認爲我可以在這種情況下編程爲超類型,並在運行時構建實例。編程到超類型的c#
public class Level
{
private readonly Ranges _range;
public Level(Ranges range)
{
_range = range;
}
public Ranges Range
{
get { return _range; }
}
public void CommonMethod()
{
throw new NotImplementedException();
}
public int CommonProperty;
}
public class ALevel : Level
{
public ALevel()
: base(new ARange())
{
}
public int ALevelProperty;
}
public class BLevel : Level
{
public BLevel()
: base(new BRange())
{
}
public int BLevelProperty;
}
public class Ranges
{
public int CommonRangeProperty;
}
public class ARange : Ranges
{
public int ARangeProperty;
public ARange()
{
}
}
public class BRange : Ranges
{
public int BRangeProperty;
}
public class ASession
{
public ASession()
{
Level = new ALevel();
}
public ALevel Level { get; set; }
}
public class BSession
{
public BSession()
{
Level = new BLevel();
}
public BLevel Level { get; set; }
}
當我創建會話對象時,它不包含ASession的特定Ranges屬性。 我只能訪問基類的屬性 aSession.Level.Range.CommonRangeProperty = 1; 但我無法訪問aSession的特定屬性 aSession.Level.Range.ARangeProperty。
我在這裏做錯了什麼?
public class Test
{
public static void Main(string[] args)
{
ASession aSession = new ASession();
aSession.Level.Range.CommonRangeProperty = 1;
//Not able to see ARangeProperty
}
}
哇! Ur解決方案簡單而強大。謝謝!但是,你能解釋我的代碼問題嗎? – sundar 2012-03-16 06:43:06
@sundar我試着用我的第一句話來解釋,「你的班級設置範圍類型爲範圍(不是具體的ARange或者BRange)」 - 這一點清楚嗎? – 2012-03-16 06:45:03
但範圍是超類型,所以我應該能夠爲它分配派生類型。 – sundar 2012-03-16 06:47:47