How would one write an Attribute that would set the default value of an auto-property
I've read the post for setting d开发者_StackOverflow中文版efault 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-
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.
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.
精彩评论