简体   繁体   English

将默认值设置为属性并使其可序列化

[英]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, adding an attribute to the property? 您是否知道在序列化之后和向属性添加属性之前可行的解决方案?

I'm working with c# with framework 3.5. 我正在使用带有框架3.5的C#。

DefaultValueAttribute 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 您可以在这里阅读很多有关序列化的信息: http : //msdn.microsoft.com/zh-cn/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()] [OnSerializing()]

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx

[OnDeserializing()] [OnDeserializing()]

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM