代码会引发有关缺少默认构造函数的

代码会引发有关缺少默认构造函数的

本文介绍了为什么以下简单的 C# 代码会引发有关缺少默认构造函数的 ProtoException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

using System.Diagnostics;
using System.IO;
using ProtoBuf;

namespace ProtoBufTest
{
    [ProtoContract]
    [ProtoInclude(13, typeof(BuildEvent))]
    public abstract class Event
    {
        [ProtoMember(1)]
        public int NodeId { get; set; }
    }

    [ProtoContract]
    public class BuildEvent : Event
    {
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var ms = new MemoryStream();
            Serializer.SerializeWithLengthPrefix<object>(ms, new BuildEvent(), PrefixStyle.Base128);

            Debug.WriteLine(ms.Position);
            ms.Position = 0;

            var ev = Serializer.DeserializeWithLengthPrefix<BuildEvent>(ms, PrefixStyle.Base128);
            Debug.WriteLine(ev.ToString());
        }
    }
}

我使用的是 protobuf-net 2.4.0.运行此代码会引发以下异常:

I am using protobuf-net 2.4.0. Running this code raises the following exception:

Unhandled Exception: ProtoBuf.ProtoException: No parameterless constructor found for ProtoBufTest.Event
   at ProtoBuf.Meta.TypeModel.ThrowCannotCreateInstance(Type type)
   at proto_4(Object , ProtoReader )
   at ProtoBuf.Serializers.CompiledSerializer.ProtoBuf.Serializers.IProtoSerializer.Read(Object value, ProtoReader source)
   at ProtoBuf.Meta.RuntimeTypeModel.Deserialize(Int32 key, Object value, ProtoReader source)
   at ProtoBuf.Meta.TypeModel.DeserializeWithLengthPrefix(Stream source, Object value, Type type, PrefixStyle style, Int32 expectedField, TypeResolver resolver, Int64& bytesRead, Boolean& haveObject, SerializationContext context)
   at ProtoBuf.Serializer.DeserializeWithLengthPrefix[T](Stream source, PrefixStyle style, Int32 fieldNumber)
   at ProtoBuf.Serializer.DeserializeWithLengthPrefix[T](Stream source, PrefixStyle style)
   at ProtoBufTest.Program.Main(String[] args) in C:\Work\ProtoBufTest\ProtoBufTest\Program.cs:line 30

推荐答案

这里使用是不对的;这就是说我知道类型 - 类型是 object".如果你没有通用友好的场景,你应该使用非通用 API - 请参阅 Serializer.NonGeneric.* 或使用 RuntimeTypeModel.Default.*;这将通过对象获得Type.

The use of <object> here is incorrect; that's saying "I know the type - the type is object". If you don't have a generic-friendly scenario, you should use the non-generic API - see Serializer.NonGeneric.* or use RuntimeTypeModel.Default.*; this will then obtain the Type via the object.

我会考虑是否应该让 自动切换到非泛型模式.

I will think about whether we should make <object> automatically switch into non-generic mode.

这篇关于为什么以下简单的 C# 代码会引发有关缺少默认构造函数的 ProtoException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:14