【问题标题】:Deserialize a .NET object of unknown type with BinaryFormatter使用 BinaryFormatter 反序列化未知类型的 .NET 对象
【发布时间】:2018-05-11 17:37:16
【问题描述】:

我正在尝试使用 BinaryFormatter 反序列化一些对象,其中序列化的对象可能包含未知类型,这些类型是从反序列化应用程序中不存在的程序集序列化的。在类型未知的情况下,我想简单地将其反序列化为空值。

我遇到了this thread on microsoft social,它没有找到解决方案。该线程链接到this question,它也没有答案,但与 xml 有关,而不是二进制格式。

【问题讨论】:

  • 尝试反序列化为动态。

标签: .net serialization binaryformatter


【解决方案1】:

这个问题可能写得更详细,但我真的不知道从哪里开始。我已经想出了解决方案,所以这里是详细信息。

首先,您必须实现SerializationBinder。在BindToType 覆盖中,您将获得程序集名称和类型名称作为字符串。当程序集名称用于您不知道的程序集时,返回一个指示它未知的标记类型;为此,我创建了一个class UnknownType {}。

class UnknownType { }

class UnknownBinder : SerializationBinder
{
    bool IsUnknown(string asmName)
    {
        // your impl here
        throw new NotImplementedException();
    }

    public override Type BindToType(string assemblyName, string typeName)
    {
        if(IsUnknown(assemblyName))
        {
            return typeof(UnknownType);
        }
        return Type.GetType(typeName);
    }
}

第二步是实现ISurrogateSelector 和ISerializationSurrogate。这些将被实现为在遇到UnknownType 时“返回null”。

class UnknownSurrogateSelector : ISurrogateSelector, ISerializationSurrogate
    {
        public void ChainSelector(ISurrogateSelector selector)
        {
        }

        public ISurrogateSelector GetNextSelector()
        {
            return null;
        }

        public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
        {
            if(type == typeof(UnknownType))
            {
                selector = this;
                return this;
            }
            selector = null;
            return null;
        }

        public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
        {
            throw new NotImplementedException();
        }

        public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        {
            if (obj is UnknownType)
                return null;
            return obj;
        }
    }

代理选择器附加到 BinaryFormatter 实例的 SurrogateSelector 成员,而活页夹附加到 Binder 成员。

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多