2009-08-24 74 views
3

有沒有辦法指定類中的[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; 
} 

回答

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

我不知道的DataContractSerializer,但XmlSerializer的會被序列化作爲「星期日星期二」。我不是WCF專家,但我認爲我在某處可以指定必須使用XmlSerializer而不是DataContractSerializer

0

我能想到的最好方法是在MyEnum上創建一個遍歷MyEnum的擴展方法。 GetMembers(),以及在序列化MyEnum時按位和非零值的方法,調用ToString()並聚合到輸出字符串。