代码之家  ›  专栏  ›  技术社区  ›  Jerod Venema

枚举能否完全序列化?

  •  1
  • Jerod Venema  · 技术社区  · 15 年前

    我有一个.NET应用程序在WCF上运行。在这个应用程序中,我定义了各种“类型”(“CourseType”、“PresentationType”、“HierarchyType”等)作为枚举。这些是自动与数据库同步的,因此我可以编写好的代码,如:

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

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

    我不知道是否有人知道一个好的方法来序列化 整个的 所以我可以在JavaScript中编写类似的语句。

    注意我是 询问是否仅序列化值。What I want is to end up with some sort of JavaScript object that looks like:

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

    我知道,我可以通过思考来做到这一点,但我希望有某种内置的解决方案…

    2 回复  |  直到 15 年前
        1
  •  1
  •   Chris Baxter    15 年前

    如果枚举是相对静态的并且不会经常更改,那么使用匿名类型的JSON序列化程序在我看来效果非常好:

    new { CourseType.Online, CourseType.Classroom }
    

    但是,如果您在不需要维护的情况下寻找处理动态或多个枚举的方法,那么可以创建一些迭代名称-值对的方法,并创建一个要序列化的字典(不需要反射)。

    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

        2
  •  0
  •   Robert Seder    15 年前

    来吧:

    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
    }
    
    推荐文章