有没有办法指定类中的[Flags]枚举字段应该序列化为字符串表示形式(例如“Sunday,Tuesday”)而不是整数值(例如5)?
更具体地说,当在Web服务中返回以下SomeClass类型时,我想获得一个名为“Days”的字符串字段,但我得到一个数字字段。
[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;
}
答案 0 :(得分:2)
不,但您可以通过创建一个执行相同操作的结构来定义自己的“枚举”,
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";
}
}
}
答案 1 :(得分:1)
我不知道DataContractSerializer,但是对于XmlSerializer,它会被序列化为“星期二星期二”。我不是WCF专家,但我想我在某处读到你可以指定必须使用XmlSerializer而不是DataContractSerializer
答案 2 :(得分:0)
我能想到的最好的方法是在MyEnum上创建一个遍历MyEnum.GetMembers()的扩展方法,以及在MyEnum被序列化的情况下按位和非零的方法,调用ToString()并聚合到输出字符串。