将对象从基类转换为子类是否有效 [英] Is it ever valid to convert an object from a base class to a subclass

查看:23
本文介绍了将对象从基类转换为子类是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在我的应用程序中(就像在许多其他应用程序中一样)一个名为 Contact 的实体,它代表任何人.在最基本的层面上,这用于表示业务联系.但是,它也可以用来代表公司的员工.还有一些特殊类型的员工(假设有一种叫做Manager)

In my application at the moment I have (as in so many other applications) an entity called Contact, which represents any person. At its most basic level this is used to represent business contacts. However it can also be used to represent employees of the company. and there are also a couple of special types of employee (let say there is one called Manager)

我试图将其建模为一种有意义的继承关系.员工有姓名和地址,就像联系人一样,以及一些与雇佣相关的属性.经理还具有许多经理特有的属性.

I am attempting to model this as an inheritance relationship which makes sense. Employees have names and addresses just like contacts, as well as a number of employment related attributes. Managers also have a number of manager specific attributes.

当员工晋升为经理时,困难就来了.将基类Employee 转换为继承类Manager 可以吗?感觉不对.我想我会在 Manager 上使用专门的构造函数来完成它.

The difficulty comes when an employee gets promoted to a manager. Is it ok to convert the base class Employee to the inheriting class Manager? It feels wrong. I guess I would do it with a specialised constructor on Manager.

顺便说一句,NHibernate 支持这种行为吗?获取员工,从员工创建经理,然后保存经理那么简单吗?

As an aside does NHibernate support this kind of behaviour? is it as simple as getting the employee, creating the manager from the employee, then saving the manager?

推荐答案

只要您的业务模式与您的领域相匹配,您就做对了.

As long as your business model matches your domain, you're doing the right thing.

但是,在我看来,您应该拥有以下内容:

However, it sounds to me like you should have something like:

Manager Promote(Employee employee)
{
   var manager = new Manager();
   //promote your employee to a manager here
   return manager;
}

在某种工作流程中.

关于 NHibernate,听起来您将 ORM 逻辑与您的业务领域混合在一起.将员工提升为经理是一种业务领域构造,因此属于您的业务模型.然而,NHibernate 如何将您的员工和经理映射到您的数据库与您的业务模型无关,除了如何映射它们.不过,这绝对与如何将员工提升为经理无关.

In regards to NHibernate, it sounds like you're mixing your ORM logic with your business domain. Promoting an Employee to a Manager is a business domain construct, and as such belongs in your business model. However, how NHibernate maps your Employees and your Managers into your DB has nothing to do with your business model, except for how to map them over. This definitely doesn't have anything to do with how to promote an employee to a manager, though.

这篇关于将对象从基类转换为子类是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆