如何编写一个属性来设置自动属性的默认值
我读过通过属性设置默认属性的帖子,该属性以 DefaultValue 结尾,用于设计模式或序列化。
但是,有没有一种方法可以编写一个属性来满足这些帖子的要求:将属性默认为某个值。
如果有一种方法——如何开始编写这样的属性?
谢谢, L-
I've read the post for setting default properties via an attribute, which end with DefaultValue is for Design Mode or Serialization.
BUT, is there a way to write an Attribute that will do what these posts require: default the property to some value.
If there is a way -- how would one start writing such an attribute?
Thanks,
L-
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上你不能。
不过,您可以在构造函数中设置默认值。
碰巧我最近确实实现了一些这样做的东西,但那是使用基于工厂的构造;工厂检查
[DefaultValue]
并通过反射设置值。但属性不能导致任意代码执行,除非您使用像 PostSharp 这样的重写器。如果构造函数距离您的喜好太远,您将必须使用字段初始化程序并针对该字段编写
get
/set
。You can't, basically.
You can set the default in the constructor, though.
As it happens I did implement something that did this very recently, but that was using factory-based construction; the factory checked for
[DefaultValue]
and set the value via reflection. But attributes can't cause arbitrary code execution unless you use a re-writer like PostSharp.If the constructor is too far away for your liking, you will have to use a field-initializer and write the
get
/set
against the field.不幸的是属性只是元数据,这意味着它们无法自行运行或执行某些操作。
但是,没有什么可以阻止您编写名称类似于
SetDefaultValues
的扩展方法,该方法从属性中读取默认值并将它们分配给属性。我在最近的一个项目中做了类似的事情,事实证明这是一个不错的决定,因为它将以声明式样式定义的所有默认值保留在一个位置。
有一篇关于 CodeProject 的 有趣的文章,深入探讨了实施
的不同策略基于 [DefaultValue]
的初始化并比较它们的性能。我建议你检查一下。Unfortunately attributes are just metadata, meaning they cannot run or do something on their own.
However nothing prevents you from writing an extension method with a name like
SetDefaultValues
that reads default values from attributes and assigns them to properties.I've done a similar thing in a recent project, and it proved to be a good decision because it kept all default values defined in a declarative style in a single place.
There is an interesting article on CodeProject peering into different strategies for implementation of
[DefaultValue]
-based initialization and comparing their performance. I suggest you check it out.