gpt4 book ai didi

c# - protobuf-net 不使用私有(private) setter 序列化 C# 属性

转载 作者:太空狗 更新时间:2023-10-29 23:23:15 35 4
gpt4 key购买 nike

我今天一直在研究 protobuf-net,遇到了一个奇怪的情况。下面的代码没有按预期反序列化。最后两次反序列化尝试成功,但它们不正确。反序列化对象将 IsEmpty 设置为 true,而实际上应将其设置为 false。我已经能够使用私有(private) setter 获取属性以进行序列化,但这个行为不正确。它与链式默认构造函数有关吗?

class Program2
{
static void Main(string[] args)
{
var comp = new FooComparer();

// this deserializes fine. woot!
using (var ms = new MemoryStream())
{
Console.WriteLine("Serializing an empty Foo");
var args1 = new Foo();
Serializer.Serialize(ms, args1);
ms.Position = 0;
var result = Serializer.Deserialize(ms);
Console.WriteLine("Serialization successful: {0}", comp.Equals(args1, result));
Console.WriteLine();
}

// this deserializes incorrectly
using (var ms = new MemoryStream())
{
Console.WriteLine("Serializing a Foo with just a string");
var args1 = new Foo("576000BJ1");
Serializer.Serialize(ms, args1);
ms.Position = 0;
var result = Serializer.Deserialize(ms);
Console.WriteLine("Serialization successful: {0}", comp.Equals(args1, result));
Console.WriteLine();
}

// this deserializes incorrectly
using (var ms = new MemoryStream())
{
Console.WriteLine("Serializing a Foo with an int");
var args1 = new Foo(42);
Serializer.Serialize(ms, args1);
ms.Position = 0;
var result = Serializer.Deserialize(ms);
Console.WriteLine("Serialization successful: {0}", comp.Equals(args1, result));
Console.WriteLine();
}

Console.WriteLine("Got dat 190% serialization");
}
}

[ProtoContract]
class Foo
{
private Foo(bool isEmpty, string fooString, int? fooInt)
{
this.IsEmpty = isEmpty;
this.FooString = fooString;
this.FooInt = fooInt;
}

public Foo() : this(true, null, null) { }
public Foo(string foo) : this(false, foo, null) { }
public Foo(int foo) : this(false, null, foo) { }

[ProtoMember(10)] public bool IsEmpty { get; private set; }
[ProtoMember(20)] public string FooString { get; private set; }
[ProtoMember(30)] public int? FooInt { get; private set; }
}

class FooComparer : IEqualityComparer
{
public bool Equals(Foo x, Foo y)
{
return (x == null && y == null) ||
(x != null && y != null &&
x.IsEmpty == y.IsEmpty &&
String.Equals(x.FooString, y.FooString, StringComparison.Ordinal) &&
x.FooInt == y.FooInt);
}

public int GetHashCode(Foo obj) { return 1; } // don't care about this
}

编辑:我正在使用 .NET 3.5 和 protobuf 2.0.0.666

最佳答案

这是隐含的默认值行为。最简单的修复可能是用 IsRequired=true 标记 IsEmpty(在 property 属性上)。

关于c# - protobuf-net 不使用私有(private) setter 序列化 C# 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19015719/

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