简体   繁体   English

序列化后如何防止序列化类的更改

[英]How to prevent changes in serialized class after serialization

I have this class: 我有这门课:

[Serializable]
public sealed class Broker
{
    public  int Id;
    public  string Name;
    public  string Hosts;
    public  string DefaultValidatorsNameSpace;
    public  string DefaultRendererNameSpace;
    public  bool IsDefault;
    public  CrmCredentials CrmCredentials;
}

This class is being deserialized when the system loads, from an xml file via XmlSerializer. 当系统从xml文件通过XmlSerializer加载时,该类被反序列化。

I don't want to allow any programmer to change the contents of the object once it has been loaded. 我不想允许任何程序员在加载对象后更改对象的内容。 One way would be to make the setter private by adding public get; private set; 一种方法是通过添加public get; private set;使setter变为私有public get; private set; public get; private set; to each item, but then I'll loose my serialization capabilities. 对每个项目,但然后我将失去我的序列化功能。

You should use DataContractSerializer to serialize your class, because it doesn't limit the serialization to public properties only. 您应该使用DataContractSerializer来序列化您的类,因为它不会仅将序列化限制为公共属性。

Also, you don't need to specify the [Serializable] attribute for XML serialization. 此外,您不需要为XML序列化指定[Serializable]属性。

YAXLib is an XML-serialization library which lets you serialize any desired fields. YAXLib是一个XML序列化库,允许您序列化任何所需的字段。 You don't need to expose the fields you need to serialize to public, you only need to set the option to serialize attributed fields only. 您不需要将序列化所需的字段公开给公共,您只需将选项设置为仅序列化属性字段。 This is how: 这是如何:

[YAXSerializableType(FieldsToSerialize=YAXSerializationFields.AttributedFieldsOnly)]
public sealed class Broker
{
    [YAXSerializableField]
    public  int Id { get; private set; }

    [YAXSerializableField]
    public  string Name { get; private set; }

    // or equaly give attribute to a private field
    [YAXSerializableField]
    private string _hosts;

    // and leave the property un-attributed
    public string Hosts { get { return _hosts; } }

}

For more information see: 有关更多信息,请参阅

http://yaxlib.codeplex.com http://yaxlib.codeplex.com

and

http://www.codeproject.com/KB/XML/yaxlib.aspx http://www.codeproject.com/KB/XML/yaxlib.aspx

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

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