gpt4 book ai didi

c# - ProtoBuf-net AsReference 需要 Activator.CreateInstance 中的公共(public)构造函数吗?

转载 作者:太空狗 更新时间:2023-10-30 01:25:18 26 4
gpt4 key购买 nike

在我的 2 个类中工作时看起来像这样(最小)

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using ProtoBuf;

namespace Sandbox
{
public partial class Form1 : Form
{
public Form1()
{
Family family = new Family();
Child child1 = new Child(1);
Child child2 = new Child(2);
Parent parent = new Parent(new List<Child>() { child1, child2 });
family.Add(parent);

string file = "sandbox.txt";

try { File.Delete(file); } catch { }

using (var fs = File.OpenWrite(file)) { Serializer.Serialize(fs, family); }
using (var fs = File.OpenRead(file)) { family = Serializer.Deserialize<Family>(fs); }

System.Diagnostics.Debug.Assert(family != null, "1. Expect family not null, but not the case.");
}
}

[ProtoContract()]
public class Child
{
[ProtoMember(1, AsReference = true)]
internal Parent Parent;

private Child() { }

public Child(int i) { }
}

[ProtoContract()]
public class Parent
{
[ProtoMember(1)]
protected List<Child> m_Children;

/// <summary>
/// ProtoBuf deserialization constructor (fails here)
/// </summary>
private Parent() { m_Children = new List<Child>(); }

public Parent(List<Child> children)
{
m_Children = children;
m_Children.ForEach(x => x.Parent = this);
}
}

[ProtoContract()]
public class Family
{
[ProtoMember(1)]
protected List<Parent> m_Parents;

public void Add(Parent parent)
{
m_Parents.Add(parent);
}

public Family()
{
m_Parents = new List<Parent>();
}
}
}

在反序列化过程中,我遇到异常“No parameterless constructor defined for this object”。用于在附近的 ProtoBuf.BclHelper 中创建 Parent 对象

case FieldObject:
// ...
value = ((options & NetObjectOptions.UseConstructor) == 0) ? BclHelpers.GetUninitializedObject(type) : Activator.CreateInstance(type);

然后当我将默认构造函数 Parent() 更改为 public 时,异常消失了。

知道 我可能忽略了 在这种情况下 AsRerference 的正确用法吗?

赏金:虽然 Marc 花时间解决了这个问题,但我需要一个明确的解决方案来在这种情况下使用 protobuf-net,通过 protobuf-net 属性、方法或其他技巧来解决。否则我将不得不完全放弃使用 protobuf-net。感谢您的帮助。

最佳答案

我相信你可以这样做来解决这个问题:

[ProtoContract(SkipConstructor = true)]
public class Parent
{
[ProtoMember(1)]
protected List<Child> m_Children;

private Parent() { Initialize(); }

[ProtoBeforeDeserialization] // could also use OnDeserializing
private void Initialize()
{
m_Children = new List<Child>();
}

public Parent(List<Child> children)
{
m_Children = children;
m_Children.ForEach(x => x.Parent = this);
}

关于c# - ProtoBuf-net AsReference 需要 Activator.CreateInstance 中的公共(public)构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7219959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com