是否可以循环遍历具有特定 DataAnnotation 和特定值的属性? .NET C#
假设我有多个属性,其自定义 DataAnnotation 属性为:
[Objective].
我只想将记录放入我的视图模型中,这些记录的值为“Y”并且用 [Objective] 属性装饰,
这种事情可能吗?
Let's say i have multiple properties with a Custom DataAnnotation Attribute of:
[Objective].
I only want to put records in my viewmodel that have the value of 'Y' AND that are decorated with an Attribute of [Objective]
Is this kind of thing possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,可以使用反射。我为 实现了类似的工厂来创建依赖属性WPF。完整的源代码可以在此处找到。
相关的代码片段:
同时,我已经在抽象类的层次结构中抽象了这种行为,因为我在创建 简化创建视图模型的工厂,但我相信上面的代码已经回答了您的问题。这个抽象“工厂”的源代码可以在这里找到。
更新:
要访问属性的值,请使用 PropertyInfo.GetValue()。您当然需要引用您的类的实例。
Yes, it is possible using reflection. I implemented something similar for a factory to create dependency properties for WPF. Entire source code can be found here.
The relevant piece of code:
Meanwhile I already abstracted this behavior in a hierarchy of abstract classes, because I did something similar when creating a factory to simplify creating view models, but I believe the above code already answers your question. Source code for this abstract 'factory' can be found here.
UPDATE:
To access the value of the property, use PropertyInfo.GetValue(). You will ofcourse need references to the instances of your class.