ここにはOOの問題があります。私は共通のプロパティと特定のプロパティを持つ2つのセッションを持っています。私は基本クラスを作成し、すべての共通プロパティ/メソッドをカプセル化しました。 2つのセッションには、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
@sundar私の最初の文章では、あなたのクラスレベルが範囲の範囲を(特定のARangeでもBRangeでもなく)設定していることを説明しようとしました。 –
ですが、Rangesはスーパータイプなので、派生型を割り当てることができます。 – sundar