为什么 System.ComponentModel.DataAnnotations.DisplayAttribute 被密封?
我打算实现一个自定义 DisplayAttribute
以允许基于模型值的动态显示值,但我不能,因为 DisplayAttribute
是密封的。
在我开始编写自己的模拟 DisplayAttribute
行为的客户属性之前,有人能想到为什么这是密封的吗?我假设它背后有一个原因,如果是这样,这可能就是我不应该尝试通过滚动自己的限制来“破解”这个限制的相同原因。
我并不是要求任何人了解微软的想法,我只是希望有人已经知道它被密封的设计原因,这样我就可以在滚动(或避免)我自己的实现时考虑到这一点。
I was going to implement a custom DisplayAttribute
in order to allow dynamic display values based on model values, but I can't because DisplayAttribute
is sealed.
Before I go off and write my own customer attribute that emulates the behavior of DisplayAttribute
, can anybody think of why this is sealed? I'm assuming there is a reason behind it, and if so, that may be the same reason I shouldn't try to "hack" around this limitation by rolling my own.
I'm not asking anyone to read Microsoft's mind, I'm just hoping someone already knows the by-design reason it's sealed, so that I can take that into account when rolling (or avoiding) my own implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,密封属性被认为是最佳实践。 FxCop 有一个关于它的规则,在此处定义。从该页面:
许多 MVC 属性(
ActionFilter
等)都是未密封的,因为它们是专门为扩展而设计的,但DataAnnotations
命名空间中的元素却不是。In general it is considered best practice to seal attributes. FxCop has a rule about it, defined here. From that page:
Many of the MVC attributes (
ActionFilter
, etc) are unsealed because they are specifically designed to be extended, but elements in theDataAnnotations
namespace are not.不完全符合您的要求,但遵循您的意图...
您仍然可以允许动态显示值,只是不会扩展 DisplayAttribute 。
相反,您可以实现自己的 IModelMetadataProvider,其中可以包含创建动态显示值所需的任何逻辑。
来自 ASP.NET MVC 团队的 Brad Wilson 在他的博客上有一篇很好的文章和示例:http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html
Not exactly what you asked, but following your intent...
You can still allow for dynamic display values, you just wont extend the DisplayAttribute.
Instead, you can implement your own IModelMetadataProvider which could contain any logic needed to create dynamic display values.
Brad Wilson, from the ASP.NET MVC team, has a good article and sample of this on his blog: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html