2010-06-27 76 views
1

我有一個運行在WCF上的.NET應用程序。在那個應用程序中,我定義了各種類型(「CourseType」,「PresentationType」,「HierarchyType」等)作爲枚舉。這些都是自動與數據庫同步,因此我可以寫漂亮的代碼,如:Enum可以完全序列化嗎?

public enum CourseType { 
    Online = 1, 
    Classroom = 2 
} 

...

if(course.Type == CourseType.Online) { 
    // do stuff on the server 
} 

是否有人知道的一個很好的方式序列化整個枚舉我想知道所以我可以在JavaScript中編寫類似的語句。

請注意,我是而不是詢問序列化的價值。我要的是帶有某種JavaScript對象的,看起來像落得:

CourseType = { 
    'online' : 1, 
    'classroom': 2 
}; 

我可以通過反射,我知道做到這一點,但我希望有某種類型的內置解決方案.. 。

回答

1

使用JSON序列化與匿名類型的作品真的很好,我認爲如果枚舉是相對靜態的,不會經常改變:

new { CourseType.Online, CourseType.Classroom } 

但是,如果你正在尋找的東西來處理動態或多個枚舉沒有維護,你可以創建一個迭代ov的東西呃名稱值對,並創建一個字典序列化(不需要反射)。

public static IDictionary<string, int> ConvertToMap(Type enumType) 
{ 
    if (enumType == null) throw new ArgumentNullException("enumType"); 
    if (!enumType.IsEnum) throw new ArgumentException("Enum type expected", "enumType"); 

    var result = new Dictionary<string, int>(); 
    foreach (int value in Enum.GetValues(enumType)) 
    result.Add(Enum.GetName(enumType, value), value); 

    return result; 
} 

編輯

如果你需要一個JSON序列......我真的很喜歡使用JSON.NET http://james.newtonking.com/projects/json-net.aspx

0

這裏亞去:

private enum CourseType 
{ 
    Online = 1, 
    Classroom = 2 
} 

private void GetCourseType() 
{ 
    StringBuilder output = new StringBuilder(); 

    string[] names = 
     Enum.GetNames(typeof(CourseType)); 

    output.AppendLine("CourseType = {"); 
    bool firstOne = true; 
    foreach (string name in names) 
    { 
     if (!firstOne) 
      output.Append(", " + Environment.NewLine); 
     output.Append(string.Format("'{0}' : {1:N0}", name, (int)Enum.Parse(typeof(CourseType), name))); 

     firstOne = false; 
    } 
    output.AppendLine(Environment.NewLine + "}"); 

    // Output that you could write out to the page... 
    Debug.WriteLine(output.ToString()); 
} 

此輸出:

CourseType = { 
'Online' : 1, 
'Classroom' : 2 
} 
相關問題