【发布时间】:2014-02-06 01:26:55
【问题描述】:
无法完全弄清楚基础/派生List<type> 的动态。主项目“Derived”引用“Base”项目。基础项目工作正常,模组需要保持在最低限度。派生项目仅添加与服务的交互,但不修改基本功能本身。
基类:
B1
{
private int _prop;
int prop
{
get{return _prop;}
set{_prop = value;}
}
}
B2
{
private List<B1> _list;
List<B1> list
{
get{return _list;}
set{_list = value;}
}
}
派生类:
D1:B1
{
int prop
{
get{return base.prop;}
set{base.prop = value;}
}
}
D2:B2
{
List<D1> list
{
get{return base.list;}/Problem area ... each base.B1 needs to be cast to a D1.
set{base.list = value;}//... each D1 needs to be cast back to a B1
}
}
base.list 中的每个 B1 都必须转换为 D1,才能使用 D1 特定的方法,这些方法又与外部服务交互。已经尝试过了,但不确定这是一个更好的策略。 (存在重载的构造函数来支持这一点。)
get
{
List<D1> listD1 = new List<D1>();
foreach (B1 b in base.list)
{
listD1.Add(new D1(B1));
}
return _listD1;
}
set
{
List<B1> listB1 = new List<B1>();
foreach (D1 d in list)
{
listB1.Add(new B1(d.prop));
}
base.list = listB1;
}
有没有更优雅的方式?
【问题讨论】:
标签: c# inheritance