列表的序列化< Enum>在C#中 [英] Serialization of a List<Enum> in C#

查看:72
本文介绍了列表的序列化< Enum>在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了序列化问题包含List< Enum>的类领域。当我序列化这个类时,一切正常,但是当我想要反序列化它时,会抛出MemberAccessException(无法创建一个抽象类。)。

如果我仅序列化Enum或Dictionary< Enum,Object>,则可以。当我有List< Enum>时,抛出异常。

我通过实现ISerializable接口并保存列表元素来解决这个问题元素

=>我想知道序列化List< Enum>中的问题在哪里字段。

---示例代码

	public static void Save(Object x)
        {
            using (FileStream fs = new FileStream("file.bin", FileMode.Create, FileAccess.Write))
            {
                new BinaryFormatter().Serialize(fs, x);
            }
        }

        public static Object Load()
        {
            using (FileStream fs = new FileStream("file.bin", FileMode.Open, FileAccess.Read))
            {
                return new BinaryFormatter().Deserialize(fs);
            }
        }

        [Serializable]
        public enum NejakyEnum
        {
            Prvni,
            Druha,
            Treti
        }

        public static void Main()
        {
            // OK
            Enum e1 = NejakyEnum.Prvni;
            Save(e1);
            Load();

            // OK
            List<NejakyEnum> l1 = new List<NejakyEnum>();
            l1.Add(NejakyEnum.Prvni);
            Save(l1);
            Load();

            // Exception
            List<Enum> l2 = new List<Enum>();
            l2.Add(NejakyEnum.Prvni);
            Save(l2);
            Load(); // -- MemberAccessException

            Console.ReadLine();
        }




推荐答案

亲爱的Lumir,

Dear Lumir,

              在第一个OK中,你只是序列化了一个NejakyEnum类型的对象,而不是Enum的类型!所以它应该工作。在第二个OK中,再次使用
序列化了一个对象(同样是!)NejakyEnum的通用列表的类型。但是第三个问题是你想要一个Enum类型的对象反序列化,它不是enum的实际类型。

               In the first OK, you just serialized an object with the type of NejakyEnum, not the type of Enum! so it should work. In the second OK, again you serialized an object with the type of a generic list of (again!) NejakyEnum. BUT the problem with the third one is that you wanna deserialize an object with the type of Enum that is not the actual type for enums.

Enum类是自定义枚举的基本ABSTRACT类型你在编写自定义枚举时,它不再是抽象类型。通常,可序列化的类必须是可初始化的,这意味着它必须具有无参数构造函数。
因为在反序列化过程中,格式化程序必须启动指定类型的实例。希望它有所帮助。

Enum class is the base ABSTRACT type for custom enumeration you made. When you write a custom enum, it is not a abstract type anymore. As a rule, a serializable class MUST be initializable which means it has to have a parameterless constructor. Because in deserialization process the formatter has to initiate an instance of the specified type. Hope it helps.

"问候<

"Regards"


这篇关于列表的序列化&lt; Enum&gt;在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆