用于更新接口实现的引用的模式

时间:2016-08-12 03:35:36

标签: c# .net design-patterns

我有以下界面:

 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)
}

问题是这不是很干 - 功能体是完全相同的。我试过这样做:

public void PrepSearchProperties(ISearchProperties query) {
    // do a bunch of stuff to query properties here
}

但是,除非我将原始query声明为ISearchProperties,否则这不会有效,这会删除实现类属性。

我可以遵循哪种模式来干我的代码?

1 个答案:

答案 0 :(得分:2)

如果您有此功能定义:

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);