2010-09-09 75 views
3

我在我的應用程序中實現了一些簡單的搜索,搜索將發生在幾個不同的對象類型(客戶,約會,活動等)上。我正在嘗試創建一個接口,它將具有可搜索的類型。我想要做的是這樣的:解決方法或替代方案接口上沒有靜態方法

public interface ISearchable 
{ 
    // Contains the 'at a glance' info from this object 
    // to show in the search results UI 
    string SearchDisplay { get; } 

    // Constructs the various ORM Criteria objects for searching the through 
    // the numerous fields on the object, excluding ones we don't want values 
    // from then calls that against the ORM and returns the results 
    static IEnumerable<ISearchable> Search(string searchFor); 
} 

我已經有一個具體實現的這個對我的領域模型對象之一,但我想將其擴展到其他人。

問題很明顯:在接口上不能有靜態方法。是否有另一種規定的方法來完成我正在尋找的內容,或者是否有解決方法?

+0

通過它的聲音,你想要做的是通過ISearchable項目IEnumerable集合搜索,如果是這種情況,那麼你就需要2班的每一位客戶,預約,活動等一會集合(Customers,Appointment和Activity):IEnumerable然後將ISearchable應用於這些集合類,並且靜態方法的需求將會消失。 – Andy 2010-09-09 22:03:46

+0

如果你真的只想要一個普通的靜態方法,那麼你將不得不做一個輔助類來包含它。 – mquander 2010-09-09 22:11:12

回答

3

接口確實指定了對象的行爲,而不是類。在這種情況下,我認爲一個解決辦法是這個分成兩個接口:

public interface ISearchDisplayable 
{ 
    // Contains the 'at a glance' info from this object 
    // to show in the search results UI 
    string SearchDisplay { get; } 
} 

public interface ISearchProvider 
{ 
    // Constructs the various ORM Criteria objects for searching the through 
    // the numerous fields on the object, excluding ones we don't want values 
    // from then calls that against the ORM and returns the results 
    IEnumerable<ISearchDisplayable> Search(string searchFor); 
} 

ISearchProvider一個實例的對象不實際的搜索,而一個ISearchDisplayable對象知道如何在搜索結果屏幕上顯示自己。

+0

這將需要我有一個我想要搜索的類的現有實例。在搜索時我不會有這些。 – 2010-09-09 22:09:18

+1

@SnOrfus,是的,我建議你改變你的設計,讓你在實例上而不是類上調用Search。 – 2010-09-09 22:10:19

+0

+1:我想我可以將這與mquander建議創建SearchProvider輔助類的建議結合起來。 – 2010-09-09 22:24:09

0

我真的不知道C#的解決方案,但根據this question,Java似乎有同樣的問題,解決方案只是使用singleton對象。

0

看起來您至少需要一個其他類,但理想情況下,您不需要爲每個ISearchable單獨設置一個類。這將您限制爲Search()的一個實現; ISearchable將不得不被寫入以適應這一點。

public class Searcher<T> where T : ISearchable 
{ 
    IEnumerable<T> Search(string searchFor); 
}