【发布时间】:2017-05-30 02:58:47
【问题描述】:
我从一个基本 DTO 派生多个 DTO(数据传输对象)。我在基础 DTO (isUpdateAvailable) 中有一个属性,该属性在 所有派生类。我有一种方法对于多个用例来说很常见,它采用基本 DTO 并直接使用它或 通过将其转换为相应的派生 DTO。
我认为这不是一个好的 c# 代码设计。应该不需要转换。而且,我还听说这种代码设计违反了一些SOLID原则。
我创建了一个简短的示例代码来描述我的观点。请看:
public class UpdateNotification
{
public void ChromeNotification(MyBaseDto baseDto, NotificationType type)
{
OnUpdateAvailable(baseDto, type);
}
public void OutlookUpdateNotification(MyBaseDto baseDto,
NotificationType type)
{
OnUpdateAvailable(baseDto, type);
}
public void OnUpdateAvailable(MyBaseDto baseDto, NotificationType type)
{
if (type == NotificationType.Chrome)
{
// it uses baseDto.IsUpdateAvailable as well as it downcast it
to DerivedAdto and uses other properties
var derivedDto = baseDto as DerivedAdto;
}
if (type == NotificationType.Outlook)
{
// currently it just uses baseDto.IsUpdateAvailable
}
}
public enum NotificationType
{
Chrome,
Outlook
}
}
我在这里重点介绍 DTO 对象的使用,它们是“MyBaseDto”、“DerivedAdto”和“DeriveddBdto”。我目前的 DTO 结构如下:
public abstract class MyBaseDto
{
public MyBaseDto(bool isUpdateAvailable)
{
IsUpdateAvailable = isUpdateAvailable;
}
public bool IsUpdateAvailable { get; }
}
public class DerivedAdto : MyBaseDto
{
public DerivedAdto(bool isUpdateAvailable)
: base(isUpdateAvailable)
{
}
public string PropertyA { get; set; }
}
public class DerivedBdto : MyBaseDto
{
public DerivedBdto(bool isUpdateAvailable)
: base(isUpdateAvailable)
{
}
}
这些 DTO 类有更好的设计吗?
我可以设计类似下面的东西吗?或者你能提出更好的方法吗?
public abstract class MyBaseDto
{
public abstract bool IsUpdateAvailable { get; set;}
}
public class DerivedAdto : MyBaseDto
{
public override bool IsUpdateAvailable { get; set;}
public string PropertyA { get; set; }
}
public class DerivedBdto : MyBaseDto
{
public override bool IsUpdateAvailable { get; set;}
}
非常感谢。
【问题讨论】:
-
我投票结束这个问题,因为它更适合 Code Review SE!
标签: c# single-responsibility-principle open-closed-principle