更新接口实现引用的模式

本文关键字:模式 引用 实现 接口 更新 | 更新日期: 2023-09-27 18:01:58

我有以下接口:

 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
}

但这并不完全工作,除非我声明原来的queryISearchProperties,剥离实现类的属性。

我可以遵循什么模式来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);