序列化/反序列化动态对象

本文关键字:对象 动态 反序列化 序列化 | 更新日期: 2023-09-27 18:20:05

我有以下类:

    public abstract class Animal
    {
        public Animal() { _myType = getAnimal(this.GetType().Name); }
        private dynamic _myType; 
        public dynamic myType { get { return _myType; } }
    }
    public class Cat : Animal
    {
        public Cat() : base() { }
    }

及其辅助功能:

    public static T CreateAnimal<T>(string animal)
    {
        Type type = Type.GetType(typeof(Form1).FullName + "+" + animal);
        return (T)Activator.CreateInstance(type);
    }
    public static dynamic getAnimal(string name)
    {
        dynamic theAnimal = Activator.CreateInstance(MyAnimals); // Will default to 'Cat'
        FieldInfo fi = MyAnimals.GetField(name);
        int iEnum = (int)fi.GetValue(MyAnimals);
        return Enum.ToObject(MyAnimals, iEnum);
    }

它从动态创建的枚举"MyAnimals"中获取其"myType":

    public static Type MyAnimals;
    public static void CreateAnimalEnum()
    {
        // Get the current application domain for the current thread.
        AppDomain currentDomain = AppDomain.CurrentDomain;
        // Create a dynamic assembly in the current application domain,  
        // and allow it to be executed and saved to disk.
        AssemblyName aName = new AssemblyName("TempAssembly");
        AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(
            aName, AssemblyBuilderAccess.Run);
        // Define a dynamic module in "TempAssembly" assembly. For a single-
        // module assembly, the module has the same name as the assembly.
        ModuleBuilder mb = ab.DefineDynamicModule(aName.Name);
        // Define a public enumeration with an underlying type of Integer.
        EnumBuilder eb = mb.DefineEnum("MyAnimalType", TypeAttributes.Public, typeof(int));
        var types = new List<Type>();
        int Count = 0;
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            try
            {
                types.AddRange(assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Animal))));
            }
            catch { }
        foreach (var type in types)
            eb.DefineLiteral(type.Name, Count++);
        // Create the type and save the assembly.
        MyAnimals = eb.CreateType();
    }

所以现在当我创建一个cat时,我无法序列化它。"InvalidOperationException:生成XML文档时出错。"(https://gist.github.com/martinnormark/2574972)但当我想序列化一个封装在另一个类中的Cat对象时,这并没有帮助。

    public static bool Save(Animal animal)
    {
        System.Xml.Serialization.XmlSerializer ListSer = new System.Xml.Serialization.XmlSerializer(typeof(Animal));
        System.IO.StreamWriter mywriter = new System.IO.StreamWriter(@"test.txt",  false);
        ListSer.Serialize(mywriter, animal);
        mywriter.Flush();
        mywriter.Close();
        return true;
    }
    public Form1()
    {
        InitializeComponent();
        GetEDIDeviceTypesEnums();
        Animal c = new Cat();
        Save(c);
        // This way fails too
        dynamic cat = CreateAnimal<Animal>("Cat");
        Save(cat);
    }

为了序列化一只猫,我缺少了什么?

序列化/反序列化动态对象

XMLSerializer需要提前知道它可以序列化哪些类型;如果在抽象类上初始化XMLSerializer,它将只知道如何序列化该类,而不知道继承它的任何东西。

XMLSerializer有另一个构造函数,它允许您输入一个额外类型的数组,以便在尝试序列化时使用。您可以从GetAssemblies动态构建该类型数组(类似于您构建自定义MyAnimals枚举所做的操作):

    public static bool Save(Animal animal)
    {
        var lListOfAnimals = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
                         from lType in lAssembly.GetTypes()
                         where typeof(Animal).IsAssignableFrom(lType)
                         select lType).ToArray();
        System.Xml.Serialization.XmlSerializer ListSer = new System.Xml.Serialization.XmlSerializer(typeof(Animal), lListOfAnimals);

代码直接从雅虎严肃的回答中提取出来。正如Yahoo Serious提到的,如果您经常调用Save,以这种方式使用Reflection可能会产生性能影响,因此您可能会缓存Animal类型的数组,而不是在每次序列化时重新构建它。