【发布时间】:2021-09-04 13:58:40
【问题描述】:
考虑以下代码示例;我希望能够使用 protobuf-net 序列化(工作正常)和反序列化(不起作用)Account 记录:
public abstract record State
{
public abstract ISet<Identity> Identities { get; }
public SerializedState Serialize()
{
using MemoryStream stream = new();
Serializer.Serialize(stream, this);
return new SerializedState(stream.ToArray(), GetType());
}
}
public sealed record Account(Identity Owner, string Identifier, decimal Balance) : State
{
public override ISet<Identity> Identities => new HashSet<Identity> {Owner};
}
ProtoBuf 合约配置有效:
RuntimeTypeModel
.Default
.Add<Account>()
.Add(nameof(Account.Owner))
.Add(nameof(Account.Identifier))
.Add(nameof(Account.Balance));
但我得到以下异常:
ProtoBuf.ProtoException:没有为 Example.Account 找到无参数构造函数
有没有办法配置反序列化(不使用属性)以允许没有无参数构造函数的记录?
【问题讨论】:
-
我认为这个之前的答案应该会有所帮助:stackoverflow.com/a/65123415/214073
-
@KijanaWoodard 我直接与 Marc Gravell 进行了交谈~in~。他说继承也是一样,稍微复杂一点,但目前还没有官方回答。
-
我不认为您可以提供minimal reproducible example 可以吗?我怀疑stackoverflow.com/a/65123415/214073 的解决方法可以工作,但是您的代码无法编译,所以我不能肯定地说。见dotnetfiddle.net/hSGMnE。
-
似乎设置
MetaType.UseConstructor = false确实有效,请参阅dotnetfiddle.net/N9siZk。这回答了你的问题了吗?如果没有,你能分享一个minimal reproducible example 显示什么不起作用吗?
标签: c# deserialization protocol-buffers protobuf-net