[英]Return generic<object> collection on interface method without casting to object in implementation
I'm looking at adding some basic search and filtering functionality in a generic/standardized way to my WCF Restful webservices. 我正在考虑以通用/标准化的方式向WCF Restful Web服务添加一些基本的搜索和筛选功能。
The idea is a client will POST a SearchRequest to any container resource ie /users or /sessions - And the server should then construct a uri to the search results and redirect to them (POST-Redirect-GET pattern). 这个想法是客户端将对任何容器资源(即/ users或/ sessions)发布SearchRequest,然后服务器应为搜索结果构造一个uri并将其重定向到它们(POST-Redirect-GET模式)。
They way I think I need to do this (Open to suggestions) is that each searchable resource should implement an interface I define. 我认为我需要这样做(建议接受)的方式是,每个可搜索资源都应实现我定义的接口。 That resource can then be used with the generic utilities I'll create for making this only a few lines of code to implement.
然后,可以将该资源与我将创建的通用实用程序一起使用,以使这几行代码得以实现。
The interface I have come up with is: 我想出的界面是:
public interface ISearchable
{
ChunkedList<object> GetAll(int chunkStart, int chunkEnd);
ChunkedList<object> SearchByValue(string searchValue, int chunkStart, int chunkEnd);
ChunkedList<object> SearchByValueWithFilters(string searchValue, List<string> filters, int chunkStart, int chunkEnd);
}
The idea being that any resource that implements this interface can do an optimized search and limit the result set (A chunked list has a collection of objects, and a prev/next chunk uri). 想法是,实现此接口的任何资源都可以进行优化搜索并限制结果集(分块列表具有对象集合和上一个/下一个分块uri)。
The problem I have is that the interface has a generic on it ChunkedList<object>
but the actual implementations want to return ChunkedList<User>
or ChunkedList<Session>
etc. and this gives me an invalid cast exception. 我的问题是该接口上具有通用的
ChunkedList<object>
但是实际的实现要返回ChunkedList<User>
或ChunkedList<Session>
等,这给了我一个无效的ChunkedList<Session>
异常。
I know I can use list.convert to manually cast each item to an object, but it would be pain for every implementation to have to do this. 我知道我可以使用list.convert手动将每个项目强制转换为对象,但是每个实现都必须这样做。
Is there a more appropriate interface or OO pattern to use for this? 是否有更合适的接口或OO模式用于此目的? For example could I achieve something "cleaner" with a base class and derive the searchable resource off of that?
例如,我可以使用基类实现某种“更清洁”的功能,并从中得出可搜索的资源吗?
public interface ISearchable<T>
{
ChunkedList<T> GetAll(int chunkStart, int chunkEnd);
ChunkedList<T> SearchByValue(string searchValue, int chunkStart, int chunkEnd);
ChunkedList<T> SearchByValueWithFilters(string searchValue, List<string> filters, int chunkStart, int chunkEnd);
}
class myClass: ISearchable<myClass>
{
ChunkedList<myClass> GetAll(int chunkStart, int chunkEnd);
ChunkedList<myClass> SearchByValue(string searchValue, int chunkStart, int chunkEnd);
ChunkedList<myClass> SearchByValueWithFilters(string searchValue, List<string> filters, int chunkStart, int chunkEnd);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.