【发布时间】:2011-10-18 03:30:21
【问题描述】:
我正在编写一些显式运算符来将数据库模型类型转换为我的域模型。像这样(简化示例):
public static explicit operator DomainModel.Role(Role roleEntity)
{
DomainModel.Role role = new DomainModel.Role
{
RoleId = roleEntity.RoleId,
Name = roleEntity.Name
};
return role;
}
但是,roleEntity 参数可能为空。大多数时候,在 .net 框架中,空实例的显式转换会导致异常。像这样:
user.Role = (DomainModel.Role)_userRepository.GetRole(user); // Would normally results in a NullReferenceException
但是如果显式操作符被调整,上面将按预期运行:
public static explicit operator DomainModel.Role(Role roleEntity)
{
DomainModel.Role role = roleEntity == null ? null : new DomainModel.Role
{
RoleId = roleEntity.RoleId,
Name = roleEntity.Name
};
return role;
}
问题:
- 创建这样的显式运算符是否合乎逻辑?
【问题讨论】:
-
我会认真考虑用命名空间前缀编写第二个角色。