protobuf-net 保存/加载静态字段
protobuff-net save / load static fields
ProtoBuffNet 中是否有保存静态字段或最佳完整静态字段的方法 class。 person.bin 保存后大小为 0,所以我认为问题在于它没有保存任何静态字段。
using ProtoBuf;
using System;
using System.IO;
using System.Windows.Forms;
namespace ProtoBuffNet
{
[ProtoContract(SkipConstructor = true)]
public class Person
{
[ProtoMember(1)]
public static int Id = -1;
[ProtoMember(2)]
public static string Name = "";
}
public partial class Form1 : Form
{
Person person = new Person();
public Form1()
{
InitializeComponent();
}
public static void setPerson()
{
Person.Id = 12345;
Person.Name = "Fred";
}
public static void resetPerson()
{
Person.Id = -1;
Person.Name = "";
}
private void button1_Click(object sender, EventArgs e)
{
setPerson();
using (var file = File.Create("person.bin"))
{
Serializer.Serialize(file, person);
}
// person Here:
// person.Id = 12345
// person.Name = "Fred"
}
private void button2_Click(object sender, EventArgs e)
{
resetPerson();
Person newPerson;
using (var file = File.OpenRead("person.bin"))
{
newPerson = Serializer.Deserialize<Person>(file);
}
// What happens:
// newPerson.Id = -1
// newPerson.Name = ""
// What I want:
// newPerson.Id = 12345
// newPerson.Name = "Fred"
}
}
}
以上代码运行,但似乎没有保存静态字段。如果 Person class 也可以是静态的,那将是最佳选择。
现在,库以实例为导向——通常是对象。坦率地说,大多数序列化工具都是。您可以使用仅将实例值代理给静态成员的 shim 对象来伪造它,但是......它并不是专门针对的场景。
ProtoBuffNet 中是否有保存静态字段或最佳完整静态字段的方法 class。 person.bin 保存后大小为 0,所以我认为问题在于它没有保存任何静态字段。
using ProtoBuf;
using System;
using System.IO;
using System.Windows.Forms;
namespace ProtoBuffNet
{
[ProtoContract(SkipConstructor = true)]
public class Person
{
[ProtoMember(1)]
public static int Id = -1;
[ProtoMember(2)]
public static string Name = "";
}
public partial class Form1 : Form
{
Person person = new Person();
public Form1()
{
InitializeComponent();
}
public static void setPerson()
{
Person.Id = 12345;
Person.Name = "Fred";
}
public static void resetPerson()
{
Person.Id = -1;
Person.Name = "";
}
private void button1_Click(object sender, EventArgs e)
{
setPerson();
using (var file = File.Create("person.bin"))
{
Serializer.Serialize(file, person);
}
// person Here:
// person.Id = 12345
// person.Name = "Fred"
}
private void button2_Click(object sender, EventArgs e)
{
resetPerson();
Person newPerson;
using (var file = File.OpenRead("person.bin"))
{
newPerson = Serializer.Deserialize<Person>(file);
}
// What happens:
// newPerson.Id = -1
// newPerson.Name = ""
// What I want:
// newPerson.Id = 12345
// newPerson.Name = "Fred"
}
}
}
以上代码运行,但似乎没有保存静态字段。如果 Person class 也可以是静态的,那将是最佳选择。
现在,库以实例为导向——通常是对象。坦率地说,大多数序列化工具都是。您可以使用仅将实例值代理给静态成员的 shim 对象来伪造它,但是......它并不是专门针对的场景。