.Net序列化-混合[Serializable]和继承树中的自定义类

5
我正在将一款Java游戏转换成C#(Puppy Games的Titan Attacks),现在几乎完成了,只剩下最后一个任务:将游戏状态序列化为保存文件。
典型的层次结构:资源(基础)-> 特性 -> 屏幕/效果/实体 -> 游戏屏幕 / 激光效果 / 入侵者。
Java代码使用标准的ObjectOutputStream / ObjectInputStream执行二进制序列化,但令人恼火的是,在基类级别(Resource)执行了一些readResolve / writeResolve工作以自定义序列化过程(如果命名资源,则不对其进行序列化,并简单地返回一个代理,其中包含稍后用于从哈希映射中获取资源的名称)。
我的天真解决方案是盲目复制此方法,并在基类中实现ISerializable,以覆盖TYPE...
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
    if (name != null) {
        // Got a name, so send a SerializedResource that just references us
        info.AddValue("name", this.name);
        info.SetType(typeof(SerializedResource));
        return;
    }

    //Serialize just MY fields (defined in Resource)
    this.SerializeMyFields(info, context, typeof(Resource));
}

问) 所以,我相当确定内置序列化的所有赌注都是关闭的,我必须沿着继承链实现ISerializable并实现序列化构造函数吗?

请注意GetObjectData是虚拟的,因此派生类可以序列化其字段,然后调用基类。 这样做可行,但要添加到大量类(100个)非常繁琐。

一些派生类型(Sprite、InvaderBehaviour等)还执行自定义序列化工作,这使情况更加复杂。

我已经查看了Jeffrey Richter关于此主题的文章,并尝试使用ResourceSurrogateSelector:ISerializationSurrogate类型结构,但是如果正在序列化的类型是资源而不是从资源派生的类型(即在序列化Invader或GameScreen时不会被调用),则这些序列化方法仅会被调用。

问) 有没有聪明的方法来做到这一点?

我设法让这两个代码库保持非常接近,这使得转换变得更容易-我想继续这种方法(因此没有XmlSerializer、Protobuf等),除非有一个真正强制性的原因。

我考虑过编写一些Java来自动化过程并反映实现Serializable接口的类型,并创建一个带有所有.Net序列化代码的.cs文件,以便不会污染主类文件(我将使它们成为部分类)

PS-目标平台将是Windows8 / Surface / XBox360上的.Net(因此版本4),可能是使用Mono的PS Vita / iOS。 保存在序列化平台上进行反序列化。

编辑 本文的Sergey Teplyakov的答案.... .NET, C#: How to add a custom serialization attribute that acts as ISerializable interface ...让我了解到ISurrogateSelector接口,它看起来将有助于选择所需的派生类。

1个回答

1

目前为止,这就是我设法想出的,我对它感到非常满意 :-) 只需要添加readResolve/writeReplace,我就完成了!(我可能还会将Object、SerializationInfo、StreamingContext参数封装在ObjectOutputStream中,以确保安全)。

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

using java.io; //My implementation of various Java classes

namespace NewSerializationTest {

public sealed class JavaSerializableSurrogateSelector : ISurrogateSelector
{
    public void ChainSelector(ISurrogateSelector selector) { throw new NotImplementedException(); }

    public ISurrogateSelector GetNextSelector() { throw new NotImplementedException(); }

    public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
    {
        if (typeof(Serializable).IsAssignableFrom(type))
        {
            selector = this;
            return new JavaSerializationSurrogate();
        }

        //Type is not marked (java.io.)Serializable
        selector = null;
        return null;
    }
}

public sealed class JavaSerializationSurrogate : ISerializationSurrogate {

    //Method called to serialize a java.io.Serializable object
    public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) {

        //Do the entire tree looking for the 'marker' methods
        var type = obj.GetType();
        while (type != null) 
        {
            var writeObject = type.GetMethod("writeObject", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext), typeof(Type) }, null );
            if (writeObject != null) {
                //Class has declared custom serialization so call through to that
                writeObject.Invoke(obj, new object[] { info, context, type });
            } else {
                //Default serialization of all non-transient fields at this level only (not the entire tree)
                obj.SerializeFields(info, context, type);
            }

            type = type.BaseType;   
        }
    }

    //Method called to deserialize a java.io.Serializable object
    public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) {

        //Do the entire tree looking for the 'marker' methods
        var type = obj.GetType();
        while (type != null) 
        {
            var readObject = type.GetMethod("readObject", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext), typeof(Type) }, null );
            if (readObject != null) {
                //Class has declared custom serialization so call through to that
                readObject.Invoke(obj, new object[] { info, context, type });
            } else {
                //Default serialization of all non-transient fields at this level only (not the entire tree)
                obj.DeserializeFields(info, context, type);
            }

            type = type.BaseType;   
        }

        return null;
    }
}

[Serializable]
class A  : java.io.Serializable {
    public string Field1;
}

[Serializable]
class B : A {
    public string Field2; 

    private void readObject(SerializationInfo stream, StreamingContext context, Type declaringType) {
        stream.defaultReadObject(context, this, declaringType);

        Debug.WriteLine("B: readObject");
    } 

    private void writeObject(SerializationInfo stream, StreamingContext context, Type declaringType) {
        stream.defaultWriteObject(context, this, declaringType);

        Debug.WriteLine("B: writeObject");
    } 
}

[Serializable]
class C: B {
    public string Field3;

    private void writeObject(SerializationInfo stream, StreamingContext context, Type declaringType) {
        stream.defaultWriteObject(context, this, declaringType);

        Debug.WriteLine("C: writeObject");
    } 
}

public static class SerializationInfoExtensions {

    public static void defaultWriteObject(this SerializationInfo info, StreamingContext context, object o, Type declaringType) {
        o.SerializeFields(info, context, declaringType);
    }

    public static void defaultReadObject(this SerializationInfo info, StreamingContext context, object o, Type declaringType) {
        o.DeserializeFields(info, context, declaringType);
    }
}

class Program {
    static void Main(string[] args) {

        var myC = new C { Field1 = "tom", Field2 = "dick", Field3 = "harry" }; 

        using (var ms = new MemoryStream()) {
            var binaryFormatter = new BinaryFormatter();
            binaryFormatter.SurrogateSelector = new JavaSerializableSurrogateSelector();

            binaryFormatter.Serialize(ms, myC);
            ms.Position = 0;
            var myCDeserialized = binaryFormatter.Deserialize(ms);
        }
    }
}

/// <summary>
/// Extensions to the object class.
/// </summary>
public static class ObjectExtensions
{
    /// <summary>
    /// Serializes an object's class fields.
    /// </summary>
    /// <param name="source">The source object to serialize.</param>
    /// <param name="info">SerializationInfo.</param>
    /// <param name="context">StreamingContext.</param>
    /// <param name="declaringType">The level in the inheritance whose fields are to be serialized - pass null to serialize the entire tree.</param>
    public static void SerializeFields(this object source, SerializationInfo info, StreamingContext context, Type declaringType)
    {
        //Serialize the entire inheritance tree if there is no declaringType passed.
        var serializeTree = declaringType == null;

        //Set the level in the class heirarchy we are interested in - if there is no declaring type use the source type (and the entire tree will be done).
        var targetType = declaringType ?? source.GetType();

        //Get the set of serializable members for the target type
        var memberInfos = FormatterServices.GetSerializableMembers(targetType, context);

        // Serialize the base class's fields to the info object
        foreach (var mi in memberInfos)
        {
            if (serializeTree || mi.DeclaringType == targetType) {
                //Specify the name to use as the key - if the entire tree is being done then the names will already have a prefix. Otherwise, we need to 
                //append the name of the declaring type.
                var name = serializeTree ? mi.Name : mi.DeclaringType.Name + "$" + mi.Name;

                info.AddValue(name, ((FieldInfo)mi).GetValue(source));
            }
        }
    }

    /// <summary>
    /// Deserializes an object's fields.
    /// </summary>
    /// <param name="source">The source object to serialize.</param>
    /// <param name="info">SerializationInfo.</param>
    /// <param name="context">StreamingContext.</param>
    /// <param name="declaringType">The level in the inheritance whose fields are to be deserialized - pass null to deserialize the entire tree.</param>
    public static void DeserializeFields(this object source, SerializationInfo info, StreamingContext context, Type declaringType)
    {
        //Deserialize the entire inheritance tree if there is no declaringType passed.
        var deserializeTree = declaringType == null;

         //Set the level in the class heirarchy we are interested in - if there is no declaring type use the source type (and the entire tree will be done).
        var targetType = declaringType ?? source.GetType();

        var memberInfos = FormatterServices.GetSerializableMembers(targetType, context);

        // Deserialize the base class's fields from the info object
        foreach (var mi in memberInfos)
        {
            //Only serialize the fields at the specific level requested.
            if (deserializeTree || mi.DeclaringType == declaringType) 
            {
                // To ease coding, treat the member as a FieldInfo object
                var fi = (FieldInfo) mi;

                //Specify the name to use as the key - if the entire tree is being done then the names will already have a prefix. Otherwise, we need to 
                //append the name of the declaring type.
                var name = deserializeTree ? mi.Name : mi.DeclaringType.Name + "$" + mi.Name;

                // Set the field to the deserialized value
                fi.SetValue(source, info.GetValue(name, fi.FieldType));
            }
        }
    }
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接