基于属性的编程有哪些优点?
我正在使用 WCF RIA 服务,并且遇到了一个使用属性的示例:
[StringLength(10, ErrorMessage="Too long")]
public string FirstName { get; set; }
...
虽然属性不限于 WCF RIA,但它让我想起了一个问题:为什么声明性或基于属性的编程比编写验证例程“老式”更合适?方式” ?
谢谢,
斯科特
I am working with WCF RIA services and have come across a sample using attributes:
[StringLength(10, ErrorMessage="Too long")]
public string FirstName { get; set; }
...
While attributes aren't restricted to WCF RIA, it reminded me of a question: why is declarative or attribute based programming perferable to coding a validation routine "the old fashioned way" ?
Thanks,
Scott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为无需执行代码即可发现约束。通过反思,您可以访问这些约束。
Because the constraint is discoverable without having to execute the code. With reflection you can access these constraints.
最大的好处是可重用性。能够设置一次(名称、必需、正则表达式等),然后在 WCF 应用程序以及 MVC 应用程序中使用它,并且一切都保持一致,这真是太棒了。
The biggest benefit is re-usability. It's great to be able to set it once (Name, Required, Regex, etc) and then use it in your WCF app, as well as your MVC app, and everything stays consistent.
这并不是说基于属性的编程优于“老式方式”验证。一般来说:
否则两种方法之间没有太大区别。
It's not that attribute based programming is superior than "old fashioned way" validation. In general:
Otherwise there is no big difference between both approaches.
使用属性时要考虑的一件事是,因为它们是可发现的,所以您可以使用它们来添加业务级客户端验证。
One thing to consider when using attributes is because they are discoverable you can use them to add business level client side validation.