简体   繁体   English

序列化只有一个类的一个属性

[英]serialize only one property of a class

I have a class which have about 20 members. 我有一个大约有20名成员的班级。 I need to serialize my the object of this class in a XML. 我需要在XML中序列化这个类的对象。 But condition is I need only one member in the XML. 但条件是我只需要XML中的一个成员。

How can I do this. 我怎样才能做到这一点。

EDIT : But at some time, I would like to serialize all the members. 编辑 :但在某个时候,我想序列化所有成员。 So I can't use [XMLIgnore] attribute. 所以我不能使用[XMLIgnore]属性。

Add the following attribute for all the members you don't want to serialize, 为您不想序列化的所有成员添加以下属性,

[XmlIgnore()]
public Type X
{
get;set;
}

You could explicitly implement the IXmlSerializable interface and control the reading/writing of the fields yourself, based on some external parameter, ie 您可以基于一些外部参数显式实现IXmlSerializable接口并自己控制字段的读/写,即

class CustomXml: IXmlSerializable
{
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        //
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        if (SerializationParameter.FullSerialization)
           //deserialize everything
        else
           //deserialize one field only
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        if (SerializationParameter.FullSerialization)
           //serialize everything
        else
           //serialize one field only
    }
}

where SerializationParameter.FullSerialization is an example of how you could control what is serialized when. 其中SerializationParameter.FullSerialization是一个如何控制何时序列化的示例。

您可以将[XmlIgnore]属性放在您不想序列化的所有成员上。

There is two ways to make properties non-serializable in.NET using attributes. 有两种方法可以使用属性在.NET中使属性不可序列化。

You may set attributes [NonSerialized] or [XmlIgnore] 您可以设置属性[NonSerialized][XmlIgnore]

If you serializing in binary or SOAP you should use [NonSerialized] , if you want to serialize just in XML you should use [XmlIgnore] . 如果使用二进制或SOAP进行序列化,则应使用[NonSerialized] ,如果要仅使用XML进行序列化,则应使用[XmlIgnore]

So in your case the answer is [XmlIgnore] 所以在你的情况下答案是[XmlIgnore]

EDIT: There is no way to apply attributes to properties dynamically. 编辑:无法动态地将属性应用于属性。 Here some info about that here: Can attributes be added dynamically in C#? 这里有一些关于此的信息: 可以在C#中动态添加属性吗? and here Remove C# attribute of a property dynamically 这里动态删除属性的C#属性

Also as a workout you may have different copies of your class with different attributes. 另外,作为锻炼,您可以使用不同属性的不同副本。

OR 要么

Have a copy of your class set all props as serializable but populate only properties you need, this way every thing else will be null/empty and after serialization of that class you should get the XML you need. 有一个类的副本将所有道具设置为可序列化,但只填充您需要的属性,这样每个其他东西都将为null / empty,并且在该类的序列化之后,您应该获得所需的XML。

mark the other attributes 标记其他属性

<NonSerializable()> _
Property someproperty

End Property 结束财产

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

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