How to make default value with a struct property?

末鹿安然 提交于 2019-12-23 10:58:08

问题


I would like to know how to apply [DefaultValue] attribute to a struct property. You can notice that Microsoft does it with Form's Size and many other properties. Their values' types are Size, Point, etc. I would want to do the same thing with my custom struct.


回答1:


[DefaultValue(typeof(Point), "0, 0")]

Would be an example. Using a string to initialize the value is a necessary evil, the kind of types you can use in an attribute constructor are very limited. Only the simple value types, string, Type and a one-dimensional array of them.

To make this work, you have to write a TypeConverter for your struct:

[TypeConverter(typeof(PointConverter))]
[// etc..]
public struct Point
{
   // etc...
}

Documentation on type converters in the MSDN library isn't great. Using the .NET type converters whose source you can look at with the Reference Source or reverse-engineer with Reflector is a great starting point to get your own working. Watch out for culture btw.




回答2:


[DefaultValue] attribute is for designer/code generator/etc only. You cannot use it for structs. structs out of all are value types and can don't support default constructor. When object of a struct is created, all of it's properties/fields are set to their default values. You cannot change this behavior.

MSDN reference:

http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

Remarks:

You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.

Note:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.




回答3:


This depends on the property type -- you can only use constant values in attributes, so it would have to be a primitive type, a string, an enum type, or any other type that is valid in const context.

So if your property is a string, you would just do something like:

[DefaultValue("foo")]
public string SomeProperty { get; private set; }

Note that this will not affect the behavior of the struct's default constructor, which will still initialize SomeProperty to null; this attribute only affects the behavior of Visual Studio's property pane.



来源:https://stackoverflow.com/questions/4572325/how-to-make-default-value-with-a-struct-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!