【发布时间】:2015-10-15 16:00:41
【问题描述】:
我必须解决一个相当棘手的问题,我会尽力解释这个问题。我有一个复杂的对象,它有两级组合,不知何故,我应该为低级组合定义两个类,并在更高级别反映新类型。为了反映低构图的变化,我也在高层次上定义了两个类。
我正在使用抽象工厂方法来创建更高级别类的实例。所有类都是可序列化的。
下图中的 C 对应于更高级别的类,A 对应于低级类。 A类的对象由二级类的对象组成,它们又由C类的对象组成。
在抽象工厂方法中,我试图反序列化对象并作为父类返回。我收到与铸造相关的错误。但是,我认为设计中存在一些我无法弄清楚的基本问题。我知道父对象不能转换为子对象。
public class A {
public virtual Double [] Prop1 { get; set; }
public virtual Double [] Prop2 { get; set; }
}
public class A1 : A {
public override double[ ] Prop1 {
get {
// implementation other than base class
}
set {
// implementation other than base class
}
}
}
public class A2 : A {
public override double[ ] Prop2 {
get {
// implementation other than base class
}
set {
// implementation other than base class
}
}
}
public class B {
public virtual A A_obj { get; set; }
}
public class B1 : B {
public override A A_obj {
get {
// want to retun the object of A1
}
set {
// want to handle the object A1
}
}
}
public class B2 : B {
public override A A_obj {
get {
// want to retun the object of A2
}
set {
// want to handle the object A2
}
}
}
public class C {
public virtual B [] B_obj { get; set; }
}
public class C1 : C {
public override B[ ] B_obj {
get {
// want to retun the object of B1
}
set {
// want to handle the object B1
}
}
}
public class C2 : C {
public override B[ ] B_obj {
get {
// want to retun the object of B2
}
set {
// want to handle the object B2
}
}
}
【问题讨论】:
-
您期望从这个设计中遇到什么样的问题?它显示了一些常见的对象树(如标准的“汽车->引擎->零件”层次结构)......
-
我在 level1implementation 类中实现 level2Obj 时遇到问题。铸造相关问题。我不能将 level2Obj 转换为 level2Implementation1Obj 或 level2Implementation2Obj
-
您可能应该提出单独的问题或将此问题转换为编码问题。如果不查看minimal reproducible example,就无法真正了解您当前的问题。
标签: c# oop inheritance composition