gpt4 book ai didi

list - 如何在不使用 ascii 文本的情况下使用 protobuf.net 保存 List

转载 作者:行者123 更新时间:2023-12-01 04:01:25 24 4
gpt4 key购买 nike

我试图将列表中的点数据保存到 protobuf.net 创建的二进制文件中。虽然我本身没有问题,但我也试图以一种在文本编辑器中不容易查看的格式保存数据。默认情况下,当您将点结构列表保存到文本文件时,每个点的 x 和 y 都显示为 ascii 文本。

    [global::ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"BufPoints", DataFormat = global::ProtoBuf.DataFormat.Default)]
private List<Point> BufPoints
{
get
{
return this.Points;
}
set
{

this.Points = value;

}
}

我曾尝试创建自己的类来保存 x 和 y double 数据,但我的例程的一部分涉及数据的深度克隆,并且在执行此克隆时这些值似乎丢失了。
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"EncodedPoints", DataFormat = global::ProtoBuf.DataFormat.Default)]
private List<Utils.PointConverter> EncodedPoints
{
get
{
List<Utils.PointConverter> temp = new List<Utils.PointConverter>();
if (Points != null)
{
foreach (Point p in this.Points)
{
temp.Add(new Utils.PointConverter(p));
}
}
return temp;
}
set
{
if (value != null)
{
this.Points = new List<Point>();
foreach (Utils.PointConverter pc in value)
{
this.Points.Add(pc.GetPoint());
}
}

}
}

PointsConverter 类如下:
    [global::System.Serializable, global::ProtoBuf.ProtoContract(Name = @"PointConverter")]
class PointConverter
{
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name = @"X", DataFormat = global::ProtoBuf.DataFormat.Default)]
public double X;

[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name = @"Y", DataFormat = global::ProtoBuf.DataFormat.Default)]
public double Y;

public PointConverter(System.Windows.Point point)
{
this.X = point.X;
this.Y = point.Y;
}

public PointConverter()
{

}

public System.Windows.Point GetPoint()
{
return new System.Windows.Point(X, Y);
}
}

我不确定为什么在深度克隆期间这些值会丢失。有没有办法以非 ascii 格式以另一种方式保存数据,或者有办法解决我的深度克隆问题?

最佳答案

首先,protobuf 在任何时候都不是 ASCII(尽管字符串值存储为 UTF-8,对于没有重音的拉丁字符,它通常看起来像 ASCII) - 我无法评论你在没有上下文的情况下看到的内容,但是序列化也不是加密。使用二进制格式可能会让人难以阅读/编辑内容,但不要将其用作安全检查的一部分。

至于代码:我认为你把事情复杂化了。实际上,对于 System.Drawing.PointSystem.Windows.Point作为“自动元组”处理的一部分,代码非常接近于自动找出映射。但不完全是!但是我们可以通过在您的应用程序启动中添加一行配置调整来简单地教育它,告诉它序列化 Point通过存储 .X作为字段 1,和 .Y作为字段 2. 这只是:

// either or both; whatever you need
model.Add(typeof(System.Windows.Point), false).Add("X", "Y");
model.Add(typeof(System.Drawing.Point), false).Add("X", "Y");

或者如果您使用默认模型实例(即 Serializer.* 方法):
// either or both; whatever you need
RuntimeTypeModel.Default.Add(typeof(System.Windows.Point), false).Add("X", "Y");
RuntimeTypeModel.Default.Add(typeof(System.Drawing.Point), false).Add("X", "Y");

而且……就是这样!这就是你所需要的。 Point成员(member)或 List<Point>Point[]现在应该正确序列化和反序列化。

关于list - 如何在不使用 ascii 文本的情况下使用 protobuf.net 保存 List<Point>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275299/

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