首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么只有在Type[]包装在对象中时才能序列化它?

问为什么只有在Type[]包装在对象中时才能序列化它?
EN

Stack Overflow用户
提问于 2020-03-25 03:55:28
回答 1查看 79关注 0票数 1

我比我想象的更多的挣扎与原型网。在简单的情况下,它是美丽的,快速的,简单的,但是我承认我有困难离开这条老路。我试图在运行时序列化和反序列化一些对象,而不是使用属性,但我发现了许多问题。第一个是这样的;在运行时,我可以序列化一个整数数组,但不能序列化类型,除非我先包装它们。以下是我的意思:

代码语言:javascript
复制
// Fails with 
// System.InvalidOperationException
// Type is not expected, and no contract can be inferred: System.RuntimeType
//   at ProtoBuf.Meta.TypeModel.ThrowUnexpectedType(Type type) in C:\Code\protobuf-net\src\protobuf-net\Meta\TypeModel.cs:line 1471
//   at ProtoBuf.Meta.TypeModel.TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, Int32 tag, Object value, Boolean isInsideList, Object parentList) in C:\Code\protobuf-net\src\protobuf-net\Meta\TypeModel.cs:line 172
//   at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value) in C:\Code\protobuf-net\src\protobuf-net\Meta\TypeModel.cs:line 194
//   at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context) in C:\Code\protobuf-net\src\protobuf-net\Meta\TypeModel.cs:line 222
//   at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance) in C:\Code\protobuf-net\src\protobuf-net\Serializer.cs:line 93
//   at my bit of code

public static void SerializeMyClass()
{
    using (var ms = new MemoryStream())
    {
        Serializer.Serialize(ms, new[] {typeof(int)});
    }
}
代码语言:javascript
复制
// Works perfectly (and deserializes correctly too, not shown here for brevity)

[ProtoContract]
public class MyClass
{
    [ProtoMember(1)] public Type[] Types;
}

public static void SerializeMyClass()
{
    using (var ms = new MemoryStream())
    {
        Serializer.Serialize(ms, new MyClass {Types = new[] {typeof(int)}});
    }
}

我有什么不明白的?是否有可能序列化一个类型数组而不首先包装它们,如果可以,我必须做什么不同的工作?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-25 09:57:01

这里的简短版本是:因为Type有特殊的处理,而且在这个场景中它从未被测试和修正过。不过,我同意这是一种奇怪和意外的行为,我已经在v3代码基在这个承诺中中修正了它。不过,此修复程序将不会被移植到v2。

请注意,在有效负载级别上,包装版本和非包装版本之间没有根本区别,因此如果没有v3修复,这里的另一个解决方法是:按照问题中的代码使用您的MyClass。

不过!我要提醒您不要过于急切地序列化Type;正如您在测试中的有效负载中所看到的那样,Type有一个不幸的特性,因为它编码了程序集元数据,如果程序集发生更改,它可能会变得很尴尬。在.NET框架和.NET核心之间,程序集确实会发生变化。您可以通过订阅类型模型上的DynamicTypeFormatting事件来解决这个问题,但是.这只是使越来越多的工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60842788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档