简体   繁体   中英

How to attribute a struct member with a default value for xml serialization in c#

I love automatic xml serialization of public members in C#. It saves you so much time. But now I may have reached the limits, or do you know how to do that?

What I want to achieve is that nothing is written for a member when it has a default value. That is is easy with a standard type like "int" for example:

[XmlElement(ElementName = "Test", IsNullable = false), DefaultValue(0)]
public int Test = 0;

So as long as "Test" equals 0 nothing is written on serialization.

But what about structs as members? For example:

    public struct Vector2 {
        public float x;
        public float y;

        public Vector2(float x = 0.0f, float y = 0.0f) {
           this.x = x;
           this.y = y;
        }
        ...
    }

    public class ToSerialize {
        [XmlElement(ElementName = "Shift", IsNullable = false), DefaultValue(new Vector2(0,0))]
        public Vector2 Shift = new Vector2(0, 0);
        ...
    }

This does not work because "new Vector2(0,0)" is not a const. Maybe I am just unable to figure out that attribute syntax. How can I make it work? This question is about coding comfort, so I am not interested in solutions like "write your own serialization code" or other proposals which result in lengthy code. If you know that this does not work with the automatic serialization system that would be an answer too.

In such cases you can use a trick to serialize another type.

[XmlIgnore]
public Vector2 Shift = new Vector2(0, 0);

[XmlElement("Shift")] // to have same name as original field/property
public string _Shift
{
    get { return ...; } // convert Vector2 to string
    set { Shift = ... value; } // opposite
}

You will have to choose type (usually string is the most appropriate) to convert into/from.

your answer is most probably in this post .

It explain how to create a boolean method that returns whether that element should be serialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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