2010-09-09 82 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); 
}