【问题标题】:Moving enums to a different assembly将枚举移动到不同的程序集
【发布时间】:2015-03-19 02:34:52
【问题描述】:

我的第一个程序集中有一个枚举类型,如下所示:

public enum MyEnum
{
   ONE,
   TWO,
   THREE
}

由于我想扩展我的应用程序,因此我决定将其移至不同的程序集 (dll) 并将其链接到我的第一个程序集。

当我这样做时,我得到了一个奇怪的结果,当我对枚举在第一个程序集中时序列化的类进行反灭菌时,默认情况下它们都返回第一个枚举成员。

有解决方法吗? 我什至尝试像这样解析它:

(MyEnum)Enum.Parse(typeof(MyEnum), serializer.MyEnumType.ToString());

没有效果。

PS。我使用二进制序列化程序,枚举在同一个命名空间中,并且仍然具有相同的名称。

[Serializable]
    public class testClass
    {
        public MyEnum En { set; get; }
    }

    public class test
    {
        void Serialize(string file)
        {
            testClass ser = new testClass();
            IFormatter formatter = new BinaryFormatter();
            System.IO.FileStream stream = new FileStream(file, FileMode.Create, System.IO.FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, ser);
            stream.Close();
        }
        void DeSerialize(string file)
        {
            IFormatter formatter = new BinaryFormatter();
            testClass ser = new testClass();
            System.IO.FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None);
            ser = (testClass)formatter.Deserialize(stream);
            stream.Close();
        }
    }

【问题讨论】:

  • 问题是,命名空间是一样的,类和枚举名也是一样。
  • @Glen 如果您仔细查看其中一篇文章,您会发现补救代码还会更改要反序列化的对象的 程序集名称。我认为这是适用于您的情况的“事情”。
  • @Glen -- 查看表明“您忘记更改程序集名称”的答案。

标签: c# .net enums .net-assembly


【解决方案1】:

BinaryFormatter 在序列化过程中考虑了关于程序集本身的各种信息,而不仅仅是类型的命名空间等。出现问题是因为您将类型移动到新程序集,因此“序列化”表示不再正确。

请参阅this question 以获得解决此问题的答案。

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2019-05-19
    相关资源
    最近更新 更多