Set a default value to a property and make it serializable
I need to set a default value for a property, but I can't do it like this:
private int prop = 1;
public Prop
{
     get { return prop;} ...
}
Because I need to serialize this class, and if I do it, I loose the default value.
Are you aware of any solution that works after the serialization and before, a开发者_如何学Cdding an attribute to the property?
I'm working with c# with framework 3.5.
DefaultValueAttribute
[DefaultValue("SomeValue")]
public string Prop { get; set; }
You can read a lot about serialization here: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
There is also:
    ''' <summary>
    ''' The defaults size for the list item.
    ''' </summary>
''' <value>Size.</value>
''' <returns>Size.</returns>
''' <remarks></remarks>
<Category("Appearance")> _
<Description("The defaults size for the list item.")> _
  Public Property DefaultItemSize() As Size Implements IVisualList.DefaultItemSize
    Get
        Return m_DefaultItemSize
    End Get
    Set(ByVal value As Size)
        m_DefaultItemSize = value
    End Set
End Property
Protected Overridable Function ShouldSerializeDefaultItemSize() As Boolean
    If m_DefaultItemSize.Equals(New Size(100, m_CellHeight)) Then Return False
    Return True
End Function
or
Another option may be to use these attributes:
[OnSerializing()]
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx
[OnDeserializing()]
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论