循环遍历 T 模型属性。建立搜索
我即将在网站上构建一个搜索页面,搜索范围将非常广泛,包含几个模型,并且每个模型都有很多属性。
有没有办法以通用方式执行此操作,或者像我在一些帖子中看到的那样使用反射器?我需要一些关于如何解决这个问题的指示或技巧。非常欣赏。
I'm about to build a search page on a website and the search is going to be extensive with a couple of models and with each model having a lot of properties.
Is there a way to do this in a generic way or use reflector as I have seen in some posts? I need some pointers or tips on how to aproach this. Highly appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用反射来获取您需要的信息。如果您有类型 T,则可以使用它
来获取所有公共属性。对于字段、方法等也是可能的。如果您需要更多元数据来生成搜索,您可以使用属性来注释属性(或字段、方法等),这就是我开始的方式。更多详细信息取决于您的具体用例。
You can use reflection to get the information you need. If you have a type T you can use
to get all public properties. Same is possible for fields, methods, ... If you need more meta data to generate your search, you can use attributes to annotate the properties (or fields, methods, ...) That's the way I would get started. Further details depend on your exact use case.
你能提供更多细节吗?
您搜索的目的是什么?请给我 30 秒的版本,以便我了解您的意图。
您打算使用正则表达式和词干提取吗?
什么样的值算作匹配?
我假设您只想搜索对象/模型的属性。正确的?
想要参观所有房产还是只参观其中的部分房产?
属性中存储什么类型的数据? (字符串、字节[]、枚举等)
头脑风暴想法:
在数据库服务器端而不是在水合对象中搜索怎么样?利用数据库可能比将所有对象加载到内存中然后反映它们更快(在运行时)。
您还可以编写一个方法来支持模型本身上下文中的搜索。您将搜索规则集作为表达式传递,然后查找匹配项。如果您有某种集合容器,则可以在该级别针对集合中的所有对象运行搜索。
如果您想要一些反射代码,我写了一些通过反射显示有关对象的大量信息的东西。这是我很久以前写的(2009 年 12 月)。我不确定它是否能达到你想要的效果。看看吧。如果它适合您,请使用它! (链接)
Can you give more details?
What is the purpose of your search? Give me the 30 second version so I can understand where you are going with this.
Are you planning on using RegEx and word stemming?
What kinds of values count as matches?
I assume you only want to search properties on the objects/models. Right?
Do want to see every property or only some of them?
What kinds of data is stored in the properties? (string, byte[], enum, etc)
Brainstorming Ideas:
What about searching one the DB server-side instead of in your hydrated objects? It might be faster (at run-time) to leverage your DB than load all of the objects into memory then reflect upon them.
You could also write a method that supports your search within the context of the model itself. You pass in the search rule set as an expression then find the match. If you have some kind of a collection container, the search could be run at that level against all of the objects in the collection.
If you want some reflection code, I wrote something that shows a lot of info about an object via reflection. I wrote this a long while ago (Dec 2009). I'm not sure if it does what you want. Take a look. If it works for you, use it! (Link)