【发布时间】:2010-12-18 08:30:07
【问题描述】:
在尝试使我的架构灵活时,我遇到了类解析问题。为简单起见,请考虑以下示例:
我有四层:UI、BL、Common 和 DAL
我的 BL 层中有一个基类,定义如下:
public class User
{
private UserDTO _d;
public User()
{
_d = new UserDTO();
}
public User(UserDTO d)
{
_d = new UserDTO(d);
}
public UserDTO D
{
get { return _d; }
set { _d = value; }
}
//static method (I cannot make it non-static due to some reasons)
public static User GetUser()
{
User user = new User(Provider.DAL.GetUser());
return user;
}
}
DTO 定义为:
public class UserDTO
{
public int ID;
public UserDTO()
{
}
public UserDTO(UserDTO source)
{
ID = source.ID;
}
}
我的 DAL 被定义为(它返回 DTO 而不是业务对象):
public static UserDTO GetUser()
{
UserDTO dto = new UserDTO();
dto.ID = 99;
return dto;
}
现在,我想“扩展”我的代码,以便在我的用户表中再添加一个字段:名称。所以我创建了一个派生的 DTO 类:
public class MyUserDTO : UserDTO
{
public string Name;
public MyUserDTO()
{
}
public MyUserDTO(MyUserDTO source)
{
Name = source.Name; //new field
base.ID = source.ID;
}
}
然后,我创建一个派生的 User 类:
public class MyUser : User
{
public MyUser()
{
this.D = new MyUserDTO();
}
}
我使用这种方法创建了我自己的自定义 DAL 提供程序:
public static UserDTO GetUser()
{
UserDTO dto = new MyUserDTO();
dto.ID = 99;
((MyUserDTO)dto).Name = "New Provider Name";
return dto;
}
现在当我在我的 BL 中访问这个 MyUserDTO 对象时,它会丢失分辨率:
User.GetUser(DAL.Provider.GetUser())
在 UI 中,我没有获得 MyUserDTO 中的属性。
是否有一种方法可以帮助我在 UI 层中获取这些属性,即使在我调用静态 User.GetUser() 方法(这反过来又会调用返回 MyUserDTO 对象的自定义提供程序)之后?
谢谢,
【问题讨论】:
标签: c# oop architecture