繁体   English   中英

如何使用 XmlSerializer 选择性地序列化字段和属性

[英]How do I Selectively Serialize Fields and Properties using XmlSerializer

问题是我有一个测试类和一个 TestVariable,我想在不序列化 TestVariable 的情况下序列化测试类。:

public class TestClass
{

    public int TestVariable
    {
        get;
        set;

    }
    public int ControlVariable
    {
        get;
        set;
    }

    public TestClass()
    {
        TestVariable = 1000;
        ControlVariable = 9999;
    }
}

执行序列化的代码:

public static void PrintClass()
{
    new XmlSerializer(typeof(TestClass)).Serialize(Console.Out, new TestClass());
}

包括命名空间 System.Xml.Serialization 并在要在序列化中排除的字段或属性上添加属性 [XmlIgnore]。

修改上面的代码,它看起来像这样:

public class TestClass
{

    [XmlIgnore]
    public int TestVariable
    {
        get;
        set;
    }

    public int ControlVariable
    {
        get;
        set;
    }

    public TestClass()
    {
        TestVariable = 1000;
        ControlVariable = 9999;
    }
}

这将导致 TestVariable 被完全排除在序列化之外。

暂无
暂无

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

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