【问题标题】:How do I Selectively Serialize Fields and Properties using XmlSerializer如何使用 XmlSerializer 选择性地序列化字段和属性
【发布时间】:2014-03-03 14:17:59
【问题描述】:

问题是我有一个测试类和一个 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());
}

【问题讨论】:

    标签: c# serialization


    【解决方案1】:

    包括命名空间 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 从序列化中完全排除。

    【讨论】:

    • 我发现这种方法不灵活,因为它是在编译时定义的。恕我直言,Conditional XML serialization 使用 ShouldSerialize* 方法更加灵活。
    • 我不得不同意它肯定不灵活,但有时您可能不需要 ShouldSerialize 方法为您提供的灵活性级别。就我而言,我有一个类,我在编译时就知道我永远不需要序列化这些值。所以我选择了一个简单的解决方案来完成这项工作。我在搜索时找不到一个非常简单的解决方案,所以我发布了我的问题和发现,以便其他人可以从中受益。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2010-12-21
    • 2021-05-15
    相关资源
    最近更新 更多