我有以下接口:
public interface ISearchProperties {
string CurrentUserLocation { get; set; }
string SearchUsername { get; set; }
}
具有以下实现:
public class BroadcastPreviewDto : ISearchProperties {
// other properties
}
public class ProfileSearchDto : ISearchProperties {
// other properties
}
我有以下功能:
public void PrepSearchProperties(ProfileSearchDto query) {
// do a bunch of stuff to query properties here (only on ISearchProperties properties)
}
public void PrepSearchProperties(BroadCastPreviewDto query) {
// do a bunch of same stuff to query properties here (only on ISearchProperties properties)
}
问题是这不是很DRY——函数体是完全一样的。我试着这样做:
public void PrepSearchProperties(ISearchProperties query) {
// do a bunch of stuff to query properties here
}
但这并不完全工作,除非我声明原来的query
为ISearchProperties
,剥离实现类的属性。
我可以遵循什么模式来DRY我的代码?
如果你有这个函数定义:
public void PrepSearchProperties(ISearchProperties query) {
// statements of the form:
query.SearchProperty = 123;
}
则可以将ISearchProperties
的任何实现传递给它。例子:
public class BroadcastPreviewDto : ISearchProperties {
// implement ISearchProperties here
// more, implementation-specific properties, e.g.
public string BroadcastType { get; set; }
}
var bp = new BroadcastPreviewDto() {
// set implementation specific properties here
BroadcastType = "example"
};
// this compiles and executes fine
PrepSearchProperties(bp);
// Same instance as before. No properties stripped.
Console.WriteLine(bp.BroadcastType);