【发布时间】:2016-08-11 16:28:52
【问题描述】:
我试图在这里最大限度地重用我的代码。我有一个SearchQueryDto,其字段如下:
public class SearchQueryDto{
// some other properties
public string SearchUsername { get; set; } // repetition 1
public string SearchProfile { get; set; } // repetition 1
public SearchInterest SearchInterest { get; set; } // repetition 1
// some other properties
}
然后,我有一个Broadcast 的数据库模型,其内容如下:
public class Broadcast {
// some other different properties
public string SearchUsername { get; set; } // repetition 1
public string SearchProfile { get; set; } // repetition 1
public SearchInterest SearchInterest { get; set; } // repetition 1
// some other different properties
public Status Status {get; set;} // repetition 2
public DateTime DateStarted {get; set;} // repetition 2
}
然后,我有一个BroadcastMessage 的数据库模型,其内容如下:
public class BroadcastMessage {
// some other properties
public Status Status {get; set;} // repetition 2
public DateTime DateStarted {get; set;} // repetition 2
}
就目前而言,添加新的搜索条件意味着我必须将字段添加到我的数据库模型Broadcast 和 DTO。如何在两个类之间共享属性?继承似乎不是答案,因为我最终可能会在 Broadcast 和其他类型之间共享属性。
我正在寻找一些简单的东西,例如:
// handles repetition 1
public class SearchCriteria{
public string SearchUsername { get; set; }
public string SearchProfile { get; set; }
public SearchInterest SearchInterest { get; set; }
}
// handles repetition 2
public class StatusProperties{
public Status Status {get; set;}
public DateTime DateStarted {get; set;}
}
public class SearchQueryDto: SearchCriteria{
// some other properties
}
public class Broadcast : SearchCriteria, StatusProperties{ // multiple inheritance :(
// some other different properties
}
public class BroadcastMessage : StatusProperties{
// some other properties
}
由于Broadcast 的需要,我不认为继承会起作用,而且我认为接口不会起作用,因为我朝错误的方向迈出了一步——更新n+1 的东西而不仅仅是@987654332 @things 为了方便编译器强制继承(不是我正在寻找的方便)。
我也不想将这些属性隐藏在另一个类的实例化之后,因为我认为这里超出了范围。
【问题讨论】:
-
也许一个解决方案是创建一个中间类来保存你想要共享的公共属性,然后你的两个类都有对该类的引用......
-
@SuperPeanut - 我喜欢这样...但是如何在不将这些对象嵌入另一个属性的情况下进行引用位?
-
您所描述的是 DTO 的主要目标:通过限制其属性并仅选择您实际想要发送的属性,您可以避免一些可能发生的问题,例如错误地序列化惰性关系(例如,如果您使用自动映射器将数据从一个对象复制到另一个对象)。
-
我只见过这种导致代码过于复杂且难以更改的情况。这些对象的用途不同,因此它们不需要从单个实现中提取。我不认为这是一个值得解决的问题。如果您认为编写代码很费力,请考虑代码生成
-
我会将它们完全分开,以尽可能最短、最有说服力的方式将每个类和属性输入为副本,并编写单元测试来断言设计一致性。
标签: c# .net composition