在继承类中创建的对象在基类中使用
为了对象序列化,我为每个对象创建了一个 DataTransferObject-Pendant。每个原始对象都有一个 ToDTO() 方法,该方法返回带有要保存的属性的适当 DTO 对象。我的大多数原始对象都是从其他对象继承的,因此我希望每个继承级别都关心它们自己的属性。一个简单的例子:
class base
{
private string _name;
public DTO_base ToDTO()
{
DTO_base result = new DTO_base();
result.Name = _name;
return result;
}
}
继承的类应该重写ToDTO()方法,调用父类方法并添加自己要保存的属性,例如:
class inherited : base
{
private string _description;
public new DTO_inherited ToDTO()
{
DTO_inherited result = base.ToDTO();
result.Description = _description;
return result;
}
}
显然,这是行不通的,因为base.ToDTO()返回一个DTO_base对象。谁能建议如何最好地实现此功能?
预先感谢,
坦率
for object serialization I created a DataTransferObject-Pendant for each of my objects. Each original object gets a ToDTO()-method that returns the appropriate DTO-Object with the properties to be saved . Most of my original objects are inherited from an other, so I would want each inheritance-level to care for their own properties. A simple example:
class base
{
private string _name;
public DTO_base ToDTO()
{
DTO_base result = new DTO_base();
result.Name = _name;
return result;
}
}
The inherited class should override the ToDTO() method, calling the parents method and adding its own properties to be saved, like:
class inherited : base
{
private string _description;
public new DTO_inherited ToDTO()
{
DTO_inherited result = base.ToDTO();
result.Description = _description;
return result;
}
}
Obviously, this wont work, because base.ToDTO() returns a DTO_base object. Can anyone suggest, how this feature would be implemented best?
Thanks in advance,
Frank
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确实希望在业务对象中拥有 DTO 创建逻辑,我会采用通用方法。
If you really want to have the DTO creation logic in your business objects, I would go for a generic approach.
我会使用模板方法:
I would use a Template Method: