2016-08-12 9 views
0

I次のインタフェースがあります。以下の実装とパターン

public interface ISearchProperties { 
    string CurrentUserLocation { get; set; } 
    string SearchUsername { get; set; } 
} 

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 class BroadcastPreviewDto : ISearchProperties { 
    // other properties 
} 
public class ProfileSearchDto : ISearchProperties { 
    // other properties 
} 

をこれはあまり乾燥していないということです - 関数本体はまったく同じものです。私はこれをやってみました:

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

をしかし、私は実装するクラスのプロパティを取り除きISearchProperties、として元queryを宣言しない限り、これはかなりの仕事をしません。

私のコードをどのようにDRYすることができますか?

+1

「ref」を絶対に使用する必要がありますか? - 単に 'public void PrepSearchProperties(ISearchProperties query)'メソッドを持たないのはなぜですか? – Corak

+0

@Corak 'Prep'から' ISearchProperties'オブジェクトを返すと、 'ISearchProperties'を私が渡している具体的な型に変換する必要があります - これは悪くないですか? – RobVious

+1

何も返品する必要はありません。実際に 'query'に新しい値を代入しない限り、' ref'は必要ありません。あなたですか?おそらく、あなたは 'ref 'が何をするのかをよく理解していないかもしれないと思うかもしれません。 – Blorgbeard

答えて

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

ありがとうございました。とても有難い。 – RobVious