Serialization [Flags] listing as string

Is it possible to indicate that the [Flags] enumeration field in the class should be serialized as a string representation (for example, "Sunday, Tuesday"), and not an integer value (for example, 5)?

To be more specific, returning the following SomeClass type in the web service, I want to get a string field called "Days", but I get a numeric field.

[Flags]
public enum DaysOfWeek
{
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}
[DataContract]
public class SomeClass
{
    [DataMember]
    public DaysOfWeek Days;
}
+3
source share
3 answers

No, but you can define your own "enum" by creating a structure that does the same,

public struct MyDayOfWeek
{
    private int iVal;
    private bool def;

    internal int Value
    {
        get { return iVal; }
        set { iVal = value; }
    }
    public bool Defined
    {
        get { return def; }
        set { def = value; }
    }
    public bool IsNull { get { return !Defined; } }

    private MyDayOfWeek(int i)
    {
       iVal = i;
       def = true;
    }           

    #region constants
    private const int Monday = new MyDayOfWeek(1);
    private const int Tuesday = new MyDayOfWeek(2);
    private const int Wednesday = new MyDayOfWeek(3);
    private const int Thursday = new MyDayOfWeek(4);
    private const int Friday = new MyDayOfWeek(5);
    private const int Saturday = new MyDayOfWeek(6);
    private const int Sunday = new MyDayOfWeek(7);
    #endregion constants

    public override string ToString()
    {
        switch (iVal)
        {
            case (1): return "Monday";
            case (2): return "Tuesday";
            case (3): return "Wednesday";
            case (4): return "Thursday";
            case (5): return "Friday";
            case (6): return "Saturday";
            case (7): return "Sunday";
        }
    }
}
+2
source

DataContractSerializer, XmlSerializer "Sunday Tuesday". WCF, , - , , XmlSerializer DataContractSerializer

+1

The best way I could think of is to create an extension method in MyEnum that iterates over MyEnum.GetMembers (), as well as those that are bitwise and non-zero, with MyEnum serialized, calling ToString () and aggregating the output line.

0
source

Source: https://habr.com/ru/post/1715904/


All Articles